babylon.max.js 4.4 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365783667836778368783697837078371783727837378374783757837678377783787837978380783817838278383783847838578386783877838878389783907839178392783937839478395783967839778398783997840078401784027840378404784057840678407784087840978410784117841278413784147841578416784177841878419784207842178422784237842478425784267842778428784297843078431784327843378434784357843678437784387843978440784417844278443784447844578446784477844878449784507845178452784537845478455784567845778458784597846078461784627846378464784657846678467784687846978470784717847278473784747847578476784777847878479784807848178482784837848478485784867848778488784897849078491784927849378494784957849678497784987849978500785017850278503785047850578506785077850878509785107851178512785137851478515785167851778518785197852078521785227852378524785257852678527785287852978530785317853278533785347853578536785377853878539785407854178542785437854478545785467854778548785497855078551785527855378554785557855678557785587855978560785617856278563785647856578566785677856878569785707857178572785737857478575785767857778578785797858078581785827858378584785857858678587785887858978590785917859278593785947859578596785977859878599786007860178602786037860478605786067860778608786097861078611786127861378614786157861678617786187861978620786217862278623786247862578626786277862878629786307863178632786337863478635786367863778638786397864078641786427864378644786457864678647786487864978650786517865278653786547865578656786577865878659786607866178662786637866478665786667866778668786697867078671786727867378674786757867678677786787867978680786817868278683786847868578686786877868878689786907869178692786937869478695786967869778698786997870078701787027870378704787057870678707787087870978710787117871278713787147871578716787177871878719787207872178722787237872478725787267872778728787297873078731787327873378734787357873678737787387873978740787417874278743787447874578746787477874878749787507875178752787537875478755787567875778758787597876078761787627876378764787657876678767787687876978770787717877278773787747877578776787777877878779787807878178782787837878478785787867878778788787897879078791787927879378794787957879678797787987879978800788017880278803788047880578806788077880878809788107881178812788137881478815788167881778818788197882078821788227882378824788257882678827788287882978830788317883278833788347883578836788377883878839788407884178842788437884478845788467884778848788497885078851788527885378854788557885678857788587885978860788617886278863788647886578866788677886878869788707887178872788737887478875788767887778878788797888078881788827888378884788857888678887788887888978890788917889278893788947889578896788977889878899789007890178902789037890478905789067890778908789097891078911789127891378914789157891678917789187891978920789217892278923789247892578926789277892878929789307893178932789337893478935789367893778938789397894078941789427894378944789457894678947789487894978950789517895278953789547895578956789577895878959789607896178962789637896478965789667896778968789697897078971789727897378974789757897678977789787897978980789817898278983789847898578986789877898878989789907899178992789937899478995789967899778998789997900079001790027900379004790057900679007790087900979010790117901279013790147901579016790177901879019790207902179022790237902479025790267902779028790297903079031790327903379034790357903679037790387903979040790417904279043790447904579046790477904879049790507905179052790537905479055790567905779058790597906079061790627906379064790657906679067790687906979070790717907279073790747907579076790777907879079790807908179082790837908479085790867908779088790897909079091790927909379094790957909679097790987909979100791017910279103791047910579106791077910879109791107911179112791137911479115791167911779118791197912079121791227912379124791257912679127791287912979130791317913279133791347913579136791377913879139791407914179142791437914479145791467914779148791497915079151791527915379154791557915679157791587915979160791617916279163791647916579166791677916879169791707917179172791737917479175791767917779178791797918079181791827918379184791857918679187791887918979190791917919279193791947919579196791977919879199792007920179202792037920479205792067920779208792097921079211792127921379214792157921679217792187921979220792217922279223792247922579226792277922879229792307923179232792337923479235792367923779238792397924079241792427924379244792457924679247792487924979250792517925279253792547925579256792577925879259792607926179262792637926479265792667926779268792697927079271792727927379274792757927679277792787927979280792817928279283792847928579286792877928879289792907929179292792937929479295792967929779298792997930079301793027930379304793057930679307793087930979310793117931279313793147931579316793177931879319793207932179322793237932479325793267932779328793297933079331793327933379334793357933679337793387933979340793417934279343793447934579346793477934879349793507935179352793537935479355793567935779358793597936079361793627936379364793657936679367793687936979370793717937279373793747937579376793777937879379793807938179382793837938479385793867938779388793897939079391793927939379394793957939679397793987939979400794017940279403794047940579406794077940879409794107941179412794137941479415794167941779418794197942079421794227942379424794257942679427794287942979430794317943279433794347943579436794377943879439794407944179442794437944479445794467944779448794497945079451794527945379454794557945679457794587945979460794617946279463794647946579466794677946879469794707947179472794737947479475794767947779478794797948079481794827948379484794857948679487794887948979490794917949279493794947949579496794977949879499795007950179502795037950479505795067950779508795097951079511795127951379514795157951679517795187951979520795217952279523795247952579526795277952879529795307953179532795337953479535795367953779538795397954079541795427954379544795457954679547795487954979550795517955279553795547955579556795577955879559795607956179562795637956479565795667956779568795697957079571795727957379574795757957679577795787957979580795817958279583795847958579586795877958879589795907959179592795937959479595795967959779598795997960079601796027960379604796057960679607796087960979610796117961279613796147961579616796177961879619796207962179622796237962479625796267962779628796297963079631796327963379634796357963679637796387963979640796417964279643796447964579646796477964879649796507965179652796537965479655796567965779658796597966079661796627966379664796657966679667796687966979670796717967279673796747967579676796777967879679796807968179682796837968479685796867968779688796897969079691796927969379694796957969679697796987969979700797017970279703797047970579706797077970879709797107971179712797137971479715797167971779718797197972079721797227972379724797257972679727797287972979730797317973279733797347973579736797377973879739797407974179742797437974479745797467974779748797497975079751797527975379754797557975679757797587975979760797617976279763797647976579766797677976879769797707977179772797737977479775797767977779778797797978079781797827978379784797857978679787797887978979790797917979279793797947979579796797977979879799798007980179802798037980479805798067980779808798097981079811798127981379814798157981679817798187981979820798217982279823798247982579826798277982879829798307983179832798337983479835798367983779838798397984079841798427984379844798457984679847798487984979850798517985279853798547985579856798577985879859798607986179862798637986479865798667986779868798697987079871798727987379874798757987679877798787987979880798817988279883798847988579886798877988879889798907989179892798937989479895798967989779898798997990079901799027990379904799057990679907799087990979910799117991279913799147991579916799177991879919799207992179922799237992479925799267992779928799297993079931799327993379934799357993679937799387993979940799417994279943799447994579946799477994879949799507995179952799537995479955799567995779958799597996079961799627996379964799657996679967799687996979970799717997279973799747997579976799777997879979799807998179982799837998479985799867998779988799897999079991799927999379994799957999679997799987999980000800018000280003800048000580006800078000880009800108001180012800138001480015800168001780018800198002080021800228002380024800258002680027800288002980030800318003280033800348003580036800378003880039800408004180042800438004480045800468004780048800498005080051800528005380054800558005680057800588005980060800618006280063800648006580066800678006880069800708007180072800738007480075800768007780078800798008080081800828008380084800858008680087800888008980090800918009280093800948009580096800978009880099801008010180102801038010480105801068010780108801098011080111801128011380114801158011680117801188011980120801218012280123801248012580126801278012880129801308013180132801338013480135801368013780138801398014080141801428014380144801458014680147801488014980150801518015280153801548015580156801578015880159801608016180162801638016480165801668016780168801698017080171801728017380174801758017680177801788017980180801818018280183801848018580186801878018880189801908019180192801938019480195801968019780198801998020080201802028020380204802058020680207802088020980210802118021280213802148021580216802178021880219802208022180222802238022480225802268022780228802298023080231802328023380234802358023680237802388023980240802418024280243802448024580246802478024880249802508025180252802538025480255802568025780258802598026080261802628026380264802658026680267802688026980270802718027280273802748027580276802778027880279802808028180282802838028480285802868028780288802898029080291802928029380294802958029680297802988029980300803018030280303803048030580306803078030880309803108031180312803138031480315803168031780318803198032080321803228032380324803258032680327803288032980330803318033280333803348033580336803378033880339803408034180342803438034480345803468034780348803498035080351803528035380354803558035680357803588035980360803618036280363803648036580366803678036880369803708037180372803738037480375803768037780378803798038080381803828038380384803858038680387803888038980390803918039280393803948039580396803978039880399804008040180402804038040480405804068040780408804098041080411804128041380414804158041680417804188041980420804218042280423804248042580426804278042880429804308043180432804338043480435804368043780438804398044080441804428044380444804458044680447804488044980450804518045280453804548045580456804578045880459804608046180462804638046480465804668046780468804698047080471804728047380474804758047680477804788047980480804818048280483804848048580486804878048880489804908049180492804938049480495804968049780498804998050080501805028050380504805058050680507805088050980510805118051280513805148051580516805178051880519805208052180522805238052480525805268052780528805298053080531805328053380534805358053680537805388053980540805418054280543805448054580546805478054880549805508055180552805538055480555805568055780558805598056080561805628056380564805658056680567805688056980570805718057280573805748057580576805778057880579805808058180582805838058480585805868058780588805898059080591805928059380594805958059680597805988059980600806018060280603806048060580606806078060880609806108061180612806138061480615806168061780618806198062080621806228062380624806258062680627806288062980630806318063280633806348063580636806378063880639806408064180642806438064480645806468064780648806498065080651806528065380654806558065680657806588065980660806618066280663806648066580666806678066880669806708067180672806738067480675806768067780678806798068080681806828068380684806858068680687806888068980690806918069280693806948069580696806978069880699807008070180702807038070480705807068070780708807098071080711807128071380714807158071680717807188071980720807218072280723807248072580726807278072880729807308073180732807338073480735807368073780738807398074080741807428074380744807458074680747807488074980750807518075280753807548075580756807578075880759807608076180762807638076480765807668076780768807698077080771807728077380774807758077680777807788077980780807818078280783807848078580786807878078880789807908079180792807938079480795807968079780798807998080080801808028080380804808058080680807808088080980810808118081280813808148081580816808178081880819808208082180822808238082480825808268082780828808298083080831808328083380834808358083680837808388083980840808418084280843808448084580846808478084880849808508085180852808538085480855808568085780858808598086080861808628086380864808658086680867808688086980870808718087280873808748087580876808778087880879808808088180882808838088480885808868088780888808898089080891808928089380894808958089680897808988089980900809018090280903809048090580906809078090880909809108091180912809138091480915809168091780918809198092080921809228092380924809258092680927809288092980930809318093280933809348093580936809378093880939809408094180942809438094480945809468094780948809498095080951809528095380954809558095680957809588095980960809618096280963809648096580966809678096880969809708097180972809738097480975809768097780978809798098080981809828098380984809858098680987809888098980990809918099280993809948099580996809978099880999810008100181002810038100481005810068100781008810098101081011810128101381014810158101681017810188101981020810218102281023810248102581026810278102881029810308103181032810338103481035810368103781038810398104081041810428104381044810458104681047810488104981050810518105281053810548105581056810578105881059810608106181062810638106481065810668106781068810698107081071810728107381074810758107681077810788107981080810818108281083810848108581086810878108881089810908109181092810938109481095810968109781098810998110081101811028110381104811058110681107811088110981110811118111281113811148111581116811178111881119811208112181122811238112481125811268112781128811298113081131811328113381134811358113681137811388113981140811418114281143811448114581146811478114881149811508115181152811538115481155811568115781158811598116081161811628116381164811658116681167811688116981170811718117281173811748117581176811778117881179811808118181182811838118481185811868118781188811898119081191811928119381194811958119681197811988119981200812018120281203812048120581206812078120881209812108121181212812138121481215812168121781218812198122081221812228122381224812258122681227812288122981230812318123281233812348123581236812378123881239812408124181242812438124481245812468124781248812498125081251812528125381254812558125681257812588125981260812618126281263812648126581266812678126881269812708127181272812738127481275812768127781278812798128081281812828128381284812858128681287812888128981290812918129281293812948129581296812978129881299813008130181302813038130481305813068130781308813098131081311813128131381314813158131681317813188131981320813218132281323813248132581326813278132881329813308133181332813338133481335813368133781338813398134081341813428134381344813458134681347813488134981350813518135281353813548135581356813578135881359813608136181362813638136481365813668136781368813698137081371813728137381374813758137681377813788137981380813818138281383813848138581386813878138881389813908139181392813938139481395813968139781398813998140081401814028140381404814058140681407814088140981410814118141281413814148141581416814178141881419814208142181422814238142481425814268142781428814298143081431814328143381434814358143681437814388143981440814418144281443814448144581446814478144881449814508145181452814538145481455814568145781458814598146081461814628146381464814658146681467814688146981470814718147281473814748147581476814778147881479814808148181482814838148481485814868148781488814898149081491814928149381494814958149681497814988149981500815018150281503815048150581506815078150881509815108151181512815138151481515815168151781518815198152081521815228152381524815258152681527815288152981530815318153281533815348153581536815378153881539815408154181542815438154481545815468154781548815498155081551815528155381554815558155681557815588155981560815618156281563815648156581566815678156881569815708157181572815738157481575815768157781578815798158081581815828158381584815858158681587815888158981590815918159281593815948159581596815978159881599816008160181602816038160481605816068160781608816098161081611816128161381614816158161681617816188161981620816218162281623816248162581626816278162881629816308163181632816338163481635816368163781638816398164081641816428164381644816458164681647816488164981650816518165281653816548165581656816578165881659816608166181662816638166481665816668166781668816698167081671816728167381674816758167681677816788167981680816818168281683816848168581686816878168881689816908169181692816938169481695816968169781698816998170081701817028170381704817058170681707817088170981710817118171281713817148171581716817178171881719817208172181722817238172481725817268172781728817298173081731817328173381734817358173681737817388173981740817418174281743817448174581746817478174881749817508175181752817538175481755817568175781758817598176081761817628176381764817658176681767817688176981770817718177281773817748177581776817778177881779817808178181782817838178481785817868178781788817898179081791817928179381794817958179681797817988179981800818018180281803818048180581806818078180881809818108181181812818138181481815818168181781818818198182081821818228182381824818258182681827818288182981830818318183281833818348183581836818378183881839818408184181842818438184481845818468184781848818498185081851818528185381854818558185681857818588185981860818618186281863818648186581866818678186881869818708187181872818738187481875818768187781878818798188081881818828188381884818858188681887818888188981890818918189281893818948189581896818978189881899819008190181902819038190481905819068190781908819098191081911819128191381914819158191681917819188191981920819218192281923819248192581926819278192881929819308193181932819338193481935819368193781938819398194081941819428194381944819458194681947819488194981950819518195281953819548195581956819578195881959819608196181962819638196481965819668196781968819698197081971819728197381974819758197681977819788197981980819818198281983819848198581986819878198881989819908199181992819938199481995819968199781998819998200082001820028200382004820058200682007820088200982010820118201282013820148201582016820178201882019820208202182022820238202482025820268202782028820298203082031820328203382034820358203682037820388203982040820418204282043820448204582046820478204882049820508205182052820538205482055820568205782058820598206082061820628206382064820658206682067820688206982070820718207282073820748207582076820778207882079820808208182082820838208482085820868208782088820898209082091820928209382094820958209682097820988209982100821018210282103821048210582106821078210882109821108211182112821138211482115821168211782118821198212082121821228212382124821258212682127821288212982130821318213282133821348213582136821378213882139821408214182142821438214482145821468214782148821498215082151821528215382154821558215682157821588215982160821618216282163821648216582166821678216882169821708217182172821738217482175821768217782178821798218082181821828218382184821858218682187821888218982190821918219282193821948219582196821978219882199822008220182202822038220482205822068220782208822098221082211822128221382214822158221682217822188221982220822218222282223822248222582226822278222882229822308223182232822338223482235822368223782238822398224082241822428224382244822458224682247822488224982250822518225282253822548225582256822578225882259822608226182262822638226482265822668226782268822698227082271822728227382274822758227682277822788227982280822818228282283822848228582286822878228882289822908229182292822938229482295822968229782298822998230082301823028230382304823058230682307823088230982310823118231282313823148231582316823178231882319823208232182322823238232482325823268232782328823298233082331823328233382334823358233682337823388233982340823418234282343823448234582346823478234882349823508235182352823538235482355823568235782358823598236082361823628236382364823658236682367823688236982370823718237282373823748237582376823778237882379823808238182382823838238482385823868238782388823898239082391823928239382394823958239682397823988239982400824018240282403824048240582406824078240882409824108241182412824138241482415824168241782418824198242082421824228242382424824258242682427824288242982430824318243282433824348243582436824378243882439824408244182442824438244482445824468244782448824498245082451824528245382454824558245682457824588245982460824618246282463824648246582466824678246882469824708247182472824738247482475824768247782478824798248082481824828248382484824858248682487824888248982490824918249282493824948249582496824978249882499825008250182502825038250482505825068250782508825098251082511825128251382514825158251682517825188251982520825218252282523825248252582526825278252882529825308253182532825338253482535825368253782538825398254082541825428254382544825458254682547825488254982550825518255282553825548255582556825578255882559825608256182562825638256482565825668256782568825698257082571825728257382574825758257682577825788257982580825818258282583825848258582586825878258882589825908259182592825938259482595825968259782598825998260082601826028260382604826058260682607826088260982610826118261282613826148261582616826178261882619826208262182622826238262482625826268262782628826298263082631826328263382634826358263682637826388263982640826418264282643826448264582646826478264882649826508265182652826538265482655826568265782658826598266082661826628266382664826658266682667826688266982670826718267282673826748267582676826778267882679826808268182682826838268482685826868268782688826898269082691826928269382694826958269682697826988269982700827018270282703827048270582706827078270882709827108271182712827138271482715827168271782718827198272082721827228272382724827258272682727827288272982730827318273282733827348273582736827378273882739827408274182742827438274482745827468274782748827498275082751827528275382754827558275682757827588275982760827618276282763827648276582766827678276882769827708277182772827738277482775827768277782778827798278082781827828278382784827858278682787827888278982790827918279282793827948279582796827978279882799828008280182802828038280482805828068280782808828098281082811828128281382814828158281682817828188281982820828218282282823828248282582826828278282882829828308283182832828338283482835828368283782838828398284082841828428284382844828458284682847828488284982850828518285282853828548285582856828578285882859828608286182862828638286482865828668286782868828698287082871828728287382874828758287682877828788287982880828818288282883828848288582886828878288882889828908289182892828938289482895828968289782898828998290082901829028290382904829058290682907829088290982910829118291282913829148291582916829178291882919829208292182922829238292482925829268292782928829298293082931829328293382934829358293682937829388293982940829418294282943829448294582946829478294882949829508295182952829538295482955829568295782958829598296082961829628296382964829658296682967829688296982970829718297282973829748297582976829778297882979829808298182982829838298482985829868298782988829898299082991829928299382994829958299682997829988299983000830018300283003830048300583006830078300883009830108301183012830138301483015830168301783018830198302083021830228302383024830258302683027830288302983030830318303283033830348303583036830378303883039830408304183042830438304483045830468304783048830498305083051830528305383054830558305683057830588305983060830618306283063830648306583066830678306883069830708307183072830738307483075830768307783078830798308083081830828308383084830858308683087830888308983090830918309283093830948309583096830978309883099831008310183102831038310483105831068310783108831098311083111831128311383114831158311683117831188311983120831218312283123831248312583126831278312883129831308313183132831338313483135831368313783138831398314083141831428314383144831458314683147831488314983150831518315283153831548315583156831578315883159831608316183162831638316483165831668316783168831698317083171831728317383174831758317683177831788317983180831818318283183831848318583186831878318883189831908319183192831938319483195831968319783198831998320083201832028320383204832058320683207832088320983210832118321283213832148321583216832178321883219832208322183222832238322483225832268322783228832298323083231832328323383234832358323683237832388323983240832418324283243832448324583246832478324883249832508325183252832538325483255832568325783258832598326083261832628326383264832658326683267832688326983270832718327283273832748327583276832778327883279832808328183282832838328483285832868328783288832898329083291832928329383294832958329683297832988329983300833018330283303833048330583306833078330883309833108331183312833138331483315833168331783318833198332083321833228332383324833258332683327833288332983330833318333283333833348333583336833378333883339833408334183342833438334483345833468334783348833498335083351833528335383354833558335683357833588335983360833618336283363833648336583366833678336883369833708337183372833738337483375833768337783378833798338083381833828338383384833858338683387833888338983390833918339283393833948339583396833978339883399834008340183402834038340483405834068340783408834098341083411834128341383414834158341683417834188341983420834218342283423834248342583426834278342883429834308343183432834338343483435834368343783438834398344083441834428344383444834458344683447834488344983450834518345283453834548345583456834578345883459834608346183462834638346483465834668346783468834698347083471834728347383474834758347683477834788347983480834818348283483834848348583486834878348883489834908349183492834938349483495834968349783498834998350083501835028350383504835058350683507835088350983510835118351283513835148351583516835178351883519835208352183522835238352483525835268352783528835298353083531835328353383534835358353683537835388353983540835418354283543835448354583546835478354883549835508355183552835538355483555835568355783558835598356083561835628356383564835658356683567835688356983570835718357283573835748357583576835778357883579835808358183582835838358483585835868358783588835898359083591835928359383594835958359683597835988359983600836018360283603836048360583606836078360883609836108361183612836138361483615836168361783618836198362083621836228362383624836258362683627836288362983630836318363283633836348363583636836378363883639836408364183642836438364483645836468364783648836498365083651836528365383654836558365683657836588365983660836618366283663836648366583666836678366883669836708367183672836738367483675836768367783678836798368083681836828368383684836858368683687836888368983690836918369283693836948369583696836978369883699837008370183702837038370483705837068370783708837098371083711837128371383714837158371683717837188371983720837218372283723837248372583726837278372883729837308373183732837338373483735837368373783738837398374083741837428374383744837458374683747837488374983750837518375283753837548375583756837578375883759837608376183762837638376483765837668376783768837698377083771837728377383774837758377683777837788377983780837818378283783837848378583786837878378883789837908379183792837938379483795837968379783798837998380083801838028380383804838058380683807838088380983810838118381283813838148381583816838178381883819838208382183822838238382483825838268382783828838298383083831838328383383834838358383683837838388383983840838418384283843838448384583846838478384883849838508385183852838538385483855838568385783858838598386083861838628386383864838658386683867838688386983870838718387283873838748387583876838778387883879838808388183882838838388483885838868388783888838898389083891838928389383894838958389683897838988389983900839018390283903839048390583906839078390883909839108391183912839138391483915839168391783918839198392083921839228392383924839258392683927839288392983930839318393283933839348393583936839378393883939839408394183942839438394483945839468394783948839498395083951839528395383954839558395683957839588395983960839618396283963839648396583966839678396883969839708397183972839738397483975839768397783978839798398083981839828398383984839858398683987839888398983990839918399283993839948399583996839978399883999840008400184002840038400484005840068400784008840098401084011840128401384014840158401684017840188401984020840218402284023840248402584026840278402884029840308403184032840338403484035840368403784038840398404084041840428404384044840458404684047840488404984050840518405284053840548405584056840578405884059840608406184062840638406484065840668406784068840698407084071840728407384074840758407684077840788407984080840818408284083840848408584086840878408884089840908409184092840938409484095840968409784098840998410084101841028410384104841058410684107841088410984110841118411284113841148411584116841178411884119841208412184122841238412484125841268412784128841298413084131841328413384134841358413684137841388413984140841418414284143841448414584146841478414884149841508415184152841538415484155841568415784158841598416084161841628416384164841658416684167841688416984170841718417284173841748417584176841778417884179841808418184182841838418484185841868418784188841898419084191841928419384194841958419684197841988419984200842018420284203842048420584206842078420884209842108421184212842138421484215842168421784218842198422084221842228422384224842258422684227842288422984230842318423284233842348423584236842378423884239842408424184242842438424484245842468424784248842498425084251842528425384254842558425684257842588425984260842618426284263842648426584266842678426884269842708427184272842738427484275842768427784278842798428084281842828428384284842858428684287842888428984290842918429284293842948429584296842978429884299843008430184302843038430484305843068430784308843098431084311843128431384314843158431684317843188431984320843218432284323843248432584326843278432884329843308433184332843338433484335843368433784338843398434084341843428434384344843458434684347843488434984350843518435284353843548435584356843578435884359843608436184362843638436484365843668436784368843698437084371843728437384374843758437684377843788437984380843818438284383843848438584386843878438884389843908439184392843938439484395843968439784398843998440084401844028440384404844058440684407844088440984410844118441284413844148441584416844178441884419844208442184422844238442484425844268442784428844298443084431844328443384434844358443684437844388443984440844418444284443844448444584446844478444884449844508445184452844538445484455844568445784458844598446084461844628446384464844658446684467844688446984470844718447284473844748447584476844778447884479844808448184482844838448484485844868448784488844898449084491844928449384494844958449684497844988449984500845018450284503845048450584506845078450884509845108451184512845138451484515845168451784518845198452084521845228452384524845258452684527845288452984530845318453284533845348453584536845378453884539845408454184542845438454484545845468454784548845498455084551845528455384554845558455684557845588455984560845618456284563845648456584566845678456884569845708457184572845738457484575845768457784578845798458084581845828458384584845858458684587845888458984590845918459284593845948459584596845978459884599846008460184602846038460484605846068460784608846098461084611846128461384614846158461684617846188461984620846218462284623846248462584626846278462884629846308463184632846338463484635846368463784638846398464084641846428464384644846458464684647846488464984650846518465284653846548465584656846578465884659846608466184662846638466484665846668466784668846698467084671846728467384674846758467684677846788467984680846818468284683846848468584686846878468884689846908469184692846938469484695846968469784698846998470084701847028470384704847058470684707847088470984710847118471284713847148471584716847178471884719847208472184722847238472484725847268472784728847298473084731847328473384734847358473684737847388473984740847418474284743847448474584746847478474884749847508475184752847538475484755847568475784758847598476084761847628476384764847658476684767847688476984770847718477284773847748477584776847778477884779847808478184782847838478484785847868478784788847898479084791847928479384794847958479684797847988479984800848018480284803848048480584806848078480884809848108481184812848138481484815848168481784818848198482084821848228482384824848258482684827848288482984830848318483284833848348483584836848378483884839848408484184842848438484484845848468484784848848498485084851848528485384854848558485684857848588485984860848618486284863848648486584866848678486884869848708487184872848738487484875848768487784878848798488084881848828488384884848858488684887848888488984890848918489284893848948489584896848978489884899849008490184902849038490484905849068490784908849098491084911849128491384914849158491684917849188491984920849218492284923849248492584926849278492884929849308493184932849338493484935849368493784938849398494084941849428494384944849458494684947849488494984950849518495284953849548495584956849578495884959849608496184962849638496484965849668496784968849698497084971849728497384974849758497684977849788497984980849818498284983849848498584986849878498884989849908499184992849938499484995849968499784998849998500085001850028500385004850058500685007850088500985010850118501285013850148501585016850178501885019850208502185022850238502485025850268502785028850298503085031850328503385034850358503685037850388503985040850418504285043850448504585046850478504885049850508505185052850538505485055850568505785058850598506085061850628506385064850658506685067850688506985070850718507285073850748507585076850778507885079850808508185082850838508485085850868508785088850898509085091850928509385094850958509685097850988509985100851018510285103851048510585106851078510885109851108511185112851138511485115851168511785118851198512085121851228512385124851258512685127851288512985130851318513285133851348513585136851378513885139851408514185142851438514485145851468514785148851498515085151851528515385154851558515685157851588515985160851618516285163851648516585166851678516885169851708517185172851738517485175851768517785178851798518085181851828518385184851858518685187851888518985190851918519285193851948519585196851978519885199852008520185202852038520485205852068520785208852098521085211852128521385214852158521685217852188521985220852218522285223852248522585226852278522885229852308523185232852338523485235852368523785238852398524085241852428524385244852458524685247852488524985250852518525285253852548525585256852578525885259852608526185262852638526485265852668526785268852698527085271852728527385274852758527685277852788527985280852818528285283852848528585286852878528885289852908529185292852938529485295852968529785298852998530085301853028530385304853058530685307853088530985310853118531285313853148531585316853178531885319853208532185322853238532485325853268532785328853298533085331853328533385334853358533685337853388533985340853418534285343853448534585346853478534885349853508535185352853538535485355853568535785358853598536085361853628536385364853658536685367853688536985370853718537285373853748537585376853778537885379853808538185382853838538485385853868538785388853898539085391853928539385394853958539685397853988539985400854018540285403854048540585406854078540885409854108541185412854138541485415854168541785418854198542085421854228542385424854258542685427854288542985430854318543285433854348543585436854378543885439854408544185442854438544485445854468544785448854498545085451854528545385454854558545685457854588545985460854618546285463854648546585466854678546885469854708547185472854738547485475854768547785478854798548085481854828548385484854858548685487854888548985490854918549285493854948549585496854978549885499855008550185502855038550485505855068550785508855098551085511855128551385514855158551685517855188551985520855218552285523855248552585526855278552885529855308553185532855338553485535855368553785538855398554085541855428554385544855458554685547855488554985550855518555285553855548555585556855578555885559855608556185562855638556485565855668556785568855698557085571855728557385574855758557685577855788557985580855818558285583855848558585586855878558885589855908559185592855938559485595855968559785598855998560085601856028560385604856058560685607856088560985610856118561285613856148561585616856178561885619856208562185622856238562485625856268562785628856298563085631856328563385634856358563685637856388563985640856418564285643856448564585646856478564885649856508565185652856538565485655856568565785658856598566085661856628566385664856658566685667856688566985670856718567285673856748567585676856778567885679856808568185682856838568485685856868568785688856898569085691856928569385694856958569685697856988569985700857018570285703857048570585706857078570885709857108571185712857138571485715857168571785718857198572085721857228572385724857258572685727857288572985730857318573285733857348573585736857378573885739857408574185742857438574485745857468574785748857498575085751857528575385754857558575685757857588575985760857618576285763857648576585766857678576885769857708577185772857738577485775857768577785778857798578085781857828578385784857858578685787857888578985790857918579285793857948579585796857978579885799858008580185802858038580485805858068580785808858098581085811858128581385814858158581685817858188581985820858218582285823858248582585826858278582885829858308583185832858338583485835858368583785838858398584085841858428584385844858458584685847858488584985850858518585285853858548585585856858578585885859858608586185862858638586485865858668586785868858698587085871858728587385874858758587685877858788587985880858818588285883858848588585886858878588885889858908589185892858938589485895858968589785898858998590085901859028590385904859058590685907859088590985910859118591285913859148591585916859178591885919859208592185922859238592485925859268592785928859298593085931859328593385934859358593685937859388593985940859418594285943859448594585946859478594885949859508595185952859538595485955859568595785958859598596085961859628596385964859658596685967859688596985970859718597285973859748597585976859778597885979859808598185982859838598485985859868598785988859898599085991859928599385994859958599685997859988599986000860018600286003860048600586006860078600886009860108601186012860138601486015860168601786018860198602086021860228602386024860258602686027860288602986030860318603286033860348603586036860378603886039860408604186042860438604486045860468604786048860498605086051860528605386054860558605686057860588605986060860618606286063860648606586066860678606886069860708607186072860738607486075860768607786078860798608086081860828608386084860858608686087860888608986090860918609286093860948609586096860978609886099861008610186102861038610486105861068610786108861098611086111861128611386114861158611686117861188611986120861218612286123861248612586126861278612886129861308613186132861338613486135861368613786138861398614086141861428614386144861458614686147861488614986150861518615286153861548615586156861578615886159861608616186162861638616486165861668616786168861698617086171861728617386174861758617686177861788617986180861818618286183861848618586186861878618886189861908619186192861938619486195861968619786198861998620086201862028620386204862058620686207862088620986210862118621286213862148621586216862178621886219862208622186222862238622486225862268622786228862298623086231862328623386234862358623686237862388623986240862418624286243862448624586246862478624886249862508625186252862538625486255862568625786258862598626086261862628626386264862658626686267862688626986270862718627286273862748627586276862778627886279862808628186282862838628486285862868628786288862898629086291862928629386294862958629686297862988629986300863018630286303863048630586306863078630886309863108631186312863138631486315863168631786318863198632086321863228632386324863258632686327863288632986330863318633286333863348633586336863378633886339863408634186342863438634486345863468634786348863498635086351863528635386354863558635686357863588635986360863618636286363863648636586366863678636886369863708637186372863738637486375863768637786378863798638086381863828638386384863858638686387863888638986390863918639286393863948639586396863978639886399864008640186402864038640486405864068640786408864098641086411864128641386414864158641686417864188641986420864218642286423864248642586426864278642886429864308643186432864338643486435864368643786438864398644086441864428644386444864458644686447864488644986450864518645286453864548645586456864578645886459864608646186462864638646486465864668646786468864698647086471864728647386474864758647686477864788647986480864818648286483864848648586486864878648886489864908649186492864938649486495864968649786498864998650086501865028650386504865058650686507865088650986510865118651286513865148651586516865178651886519865208652186522865238652486525865268652786528865298653086531865328653386534865358653686537865388653986540865418654286543865448654586546865478654886549865508655186552865538655486555865568655786558865598656086561865628656386564865658656686567865688656986570865718657286573865748657586576865778657886579865808658186582865838658486585865868658786588865898659086591865928659386594865958659686597865988659986600866018660286603866048660586606866078660886609866108661186612866138661486615866168661786618866198662086621866228662386624866258662686627866288662986630866318663286633866348663586636866378663886639866408664186642866438664486645866468664786648866498665086651866528665386654866558665686657866588665986660866618666286663866648666586666866678666886669866708667186672866738667486675866768667786678866798668086681866828668386684866858668686687866888668986690866918669286693866948669586696866978669886699867008670186702867038670486705867068670786708867098671086711867128671386714867158671686717867188671986720867218672286723867248672586726867278672886729867308673186732867338673486735867368673786738867398674086741867428674386744867458674686747867488674986750867518675286753867548675586756867578675886759867608676186762867638676486765867668676786768867698677086771867728677386774867758677686777867788677986780867818678286783867848678586786867878678886789867908679186792867938679486795867968679786798867998680086801868028680386804868058680686807868088680986810868118681286813868148681586816868178681886819868208682186822868238682486825868268682786828868298683086831868328683386834868358683686837868388683986840868418684286843868448684586846868478684886849868508685186852868538685486855868568685786858868598686086861868628686386864868658686686867868688686986870868718687286873868748687586876868778687886879868808688186882868838688486885868868688786888868898689086891868928689386894868958689686897868988689986900869018690286903869048690586906869078690886909869108691186912869138691486915869168691786918869198692086921869228692386924869258692686927869288692986930869318693286933869348693586936869378693886939869408694186942869438694486945869468694786948869498695086951869528695386954869558695686957869588695986960869618696286963869648696586966869678696886969869708697186972869738697486975869768697786978869798698086981869828698386984869858698686987869888698986990869918699286993869948699586996869978699886999870008700187002870038700487005870068700787008870098701087011870128701387014870158701687017870188701987020870218702287023870248702587026870278702887029870308703187032870338703487035870368703787038870398704087041870428704387044870458704687047870488704987050870518705287053870548705587056870578705887059870608706187062870638706487065870668706787068870698707087071870728707387074870758707687077870788707987080870818708287083870848708587086870878708887089870908709187092870938709487095870968709787098870998710087101871028710387104871058710687107871088710987110871118711287113871148711587116871178711887119871208712187122871238712487125871268712787128871298713087131871328713387134871358713687137871388713987140871418714287143871448714587146871478714887149871508715187152871538715487155871568715787158871598716087161871628716387164871658716687167871688716987170871718717287173871748717587176871778717887179871808718187182871838718487185871868718787188871898719087191871928719387194871958719687197871988719987200872018720287203872048720587206872078720887209872108721187212872138721487215872168721787218872198722087221872228722387224872258722687227872288722987230872318723287233872348723587236872378723887239872408724187242872438724487245872468724787248872498725087251872528725387254872558725687257872588725987260872618726287263872648726587266872678726887269872708727187272872738727487275872768727787278872798728087281872828728387284872858728687287872888728987290872918729287293872948729587296872978729887299873008730187302873038730487305873068730787308873098731087311873128731387314873158731687317873188731987320873218732287323873248732587326873278732887329873308733187332873338733487335873368733787338873398734087341873428734387344873458734687347873488734987350873518735287353873548735587356873578735887359873608736187362873638736487365873668736787368873698737087371873728737387374873758737687377873788737987380873818738287383873848738587386873878738887389873908739187392873938739487395873968739787398873998740087401874028740387404874058740687407874088740987410874118741287413874148741587416874178741887419874208742187422874238742487425874268742787428874298743087431874328743387434874358743687437874388743987440874418744287443874448744587446874478744887449874508745187452874538745487455874568745787458874598746087461874628746387464874658746687467874688746987470874718747287473874748747587476874778747887479874808748187482874838748487485874868748787488874898749087491874928749387494874958749687497874988749987500875018750287503875048750587506875078750887509875108751187512875138751487515875168751787518875198752087521875228752387524875258752687527875288752987530875318753287533875348753587536875378753887539875408754187542875438754487545875468754787548875498755087551875528755387554875558755687557875588755987560875618756287563875648756587566875678756887569875708757187572875738757487575875768757787578875798758087581875828758387584875858758687587875888758987590875918759287593875948759587596875978759887599876008760187602876038760487605876068760787608876098761087611876128761387614876158761687617876188761987620876218762287623876248762587626876278762887629876308763187632876338763487635876368763787638876398764087641876428764387644876458764687647876488764987650876518765287653876548765587656876578765887659876608766187662876638766487665876668766787668876698767087671876728767387674876758767687677876788767987680876818768287683876848768587686876878768887689876908769187692876938769487695876968769787698876998770087701877028770387704877058770687707877088770987710877118771287713877148771587716877178771887719877208772187722877238772487725877268772787728877298773087731877328773387734877358773687737877388773987740877418774287743877448774587746877478774887749877508775187752877538775487755877568775787758877598776087761877628776387764877658776687767877688776987770877718777287773877748777587776877778777887779877808778187782877838778487785877868778787788877898779087791877928779387794877958779687797877988779987800878018780287803878048780587806878078780887809878108781187812878138781487815878168781787818878198782087821878228782387824878258782687827878288782987830878318783287833878348783587836878378783887839878408784187842878438784487845878468784787848878498785087851878528785387854878558785687857878588785987860878618786287863878648786587866878678786887869878708787187872878738787487875878768787787878878798788087881878828788387884878858788687887878888788987890878918789287893878948789587896878978789887899879008790187902879038790487905879068790787908879098791087911879128791387914879158791687917879188791987920879218792287923879248792587926879278792887929879308793187932879338793487935879368793787938879398794087941879428794387944879458794687947879488794987950879518795287953879548795587956879578795887959879608796187962879638796487965879668796787968879698797087971879728797387974879758797687977879788797987980879818798287983879848798587986879878798887989879908799187992879938799487995879968799787998879998800088001880028800388004880058800688007880088800988010880118801288013880148801588016880178801888019880208802188022880238802488025880268802788028880298803088031880328803388034880358803688037880388803988040880418804288043880448804588046880478804888049880508805188052880538805488055880568805788058880598806088061880628806388064880658806688067880688806988070880718807288073880748807588076880778807888079880808808188082880838808488085880868808788088880898809088091880928809388094880958809688097880988809988100881018810288103881048810588106881078810888109881108811188112881138811488115881168811788118881198812088121881228812388124881258812688127881288812988130881318813288133881348813588136881378813888139881408814188142881438814488145881468814788148881498815088151881528815388154881558815688157881588815988160881618816288163881648816588166881678816888169881708817188172881738817488175881768817788178881798818088181881828818388184881858818688187881888818988190881918819288193881948819588196881978819888199882008820188202882038820488205882068820788208882098821088211882128821388214882158821688217882188821988220882218822288223882248822588226882278822888229882308823188232882338823488235882368823788238882398824088241882428824388244882458824688247882488824988250882518825288253882548825588256882578825888259882608826188262882638826488265882668826788268882698827088271882728827388274882758827688277882788827988280882818828288283882848828588286882878828888289882908829188292882938829488295882968829788298882998830088301883028830388304883058830688307883088830988310883118831288313883148831588316883178831888319883208832188322883238832488325883268832788328883298833088331883328833388334883358833688337883388833988340883418834288343883448834588346883478834888349883508835188352883538835488355883568835788358883598836088361883628836388364883658836688367883688836988370883718837288373883748837588376883778837888379883808838188382883838838488385883868838788388883898839088391883928839388394883958839688397883988839988400884018840288403884048840588406884078840888409884108841188412884138841488415884168841788418884198842088421884228842388424884258842688427884288842988430884318843288433884348843588436884378843888439884408844188442884438844488445884468844788448884498845088451884528845388454884558845688457884588845988460884618846288463884648846588466884678846888469884708847188472884738847488475884768847788478884798848088481884828848388484884858848688487884888848988490884918849288493884948849588496884978849888499885008850188502885038850488505885068850788508885098851088511885128851388514885158851688517885188851988520885218852288523885248852588526885278852888529885308853188532885338853488535885368853788538885398854088541885428854388544885458854688547885488854988550885518855288553885548855588556885578855888559885608856188562885638856488565885668856788568885698857088571885728857388574885758857688577885788857988580885818858288583885848858588586885878858888589885908859188592885938859488595885968859788598885998860088601886028860388604886058860688607886088860988610886118861288613886148861588616886178861888619886208862188622886238862488625886268862788628886298863088631886328863388634886358863688637886388863988640886418864288643886448864588646886478864888649886508865188652886538865488655886568865788658886598866088661886628866388664886658866688667886688866988670886718867288673886748867588676886778867888679886808868188682886838868488685886868868788688886898869088691886928869388694886958869688697886988869988700887018870288703887048870588706887078870888709887108871188712887138871488715887168871788718887198872088721887228872388724887258872688727887288872988730887318873288733887348873588736887378873888739887408874188742887438874488745887468874788748887498875088751887528875388754887558875688757887588875988760887618876288763887648876588766887678876888769887708877188772887738877488775887768877788778887798878088781887828878388784887858878688787887888878988790887918879288793887948879588796887978879888799888008880188802888038880488805888068880788808888098881088811888128881388814888158881688817888188881988820888218882288823888248882588826888278882888829888308883188832888338883488835888368883788838888398884088841888428884388844888458884688847888488884988850888518885288853888548885588856888578885888859888608886188862888638886488865888668886788868888698887088871888728887388874888758887688877888788887988880888818888288883888848888588886888878888888889888908889188892888938889488895888968889788898888998890088901889028890388904889058890688907889088890988910889118891288913889148891588916889178891888919889208892188922889238892488925889268892788928889298893088931889328893388934889358893688937889388893988940889418894288943889448894588946889478894888949889508895188952889538895488955889568895788958889598896088961889628896388964889658896688967889688896988970889718897288973889748897588976889778897888979889808898188982889838898488985889868898788988889898899088991889928899388994889958899688997889988899989000890018900289003890048900589006890078900889009890108901189012890138901489015890168901789018890198902089021890228902389024890258902689027890288902989030890318903289033890348903589036890378903889039890408904189042890438904489045890468904789048890498905089051890528905389054890558905689057890588905989060890618906289063890648906589066890678906889069890708907189072890738907489075890768907789078890798908089081890828908389084890858908689087890888908989090890918909289093890948909589096890978909889099891008910189102891038910489105891068910789108891098911089111891128911389114891158911689117891188911989120891218912289123891248912589126891278912889129891308913189132891338913489135891368913789138891398914089141891428914389144891458914689147891488914989150891518915289153891548915589156891578915889159891608916189162891638916489165891668916789168891698917089171891728917389174891758917689177891788917989180891818918289183891848918589186891878918889189891908919189192891938919489195891968919789198891998920089201892028920389204892058920689207892088920989210892118921289213892148921589216892178921889219892208922189222892238922489225892268922789228892298923089231892328923389234892358923689237892388923989240892418924289243892448924589246892478924889249892508925189252892538925489255892568925789258892598926089261892628926389264892658926689267892688926989270892718927289273892748927589276892778927889279892808928189282892838928489285892868928789288892898929089291892928929389294892958929689297892988929989300893018930289303893048930589306893078930889309893108931189312893138931489315893168931789318893198932089321893228932389324893258932689327893288932989330893318933289333893348933589336893378933889339893408934189342893438934489345893468934789348893498935089351893528935389354893558935689357893588935989360893618936289363893648936589366893678936889369893708937189372893738937489375893768937789378893798938089381893828938389384893858938689387893888938989390893918939289393893948939589396893978939889399894008940189402894038940489405894068940789408894098941089411894128941389414894158941689417894188941989420894218942289423894248942589426894278942889429894308943189432894338943489435894368943789438894398944089441894428944389444894458944689447894488944989450894518945289453894548945589456894578945889459894608946189462894638946489465894668946789468894698947089471894728947389474894758947689477894788947989480894818948289483894848948589486894878948889489894908949189492894938949489495894968949789498894998950089501895028950389504895058950689507895088950989510895118951289513895148951589516895178951889519895208952189522895238952489525895268952789528895298953089531895328953389534895358953689537895388953989540895418954289543895448954589546895478954889549895508955189552895538955489555895568955789558895598956089561895628956389564895658956689567895688956989570895718957289573895748957589576895778957889579895808958189582895838958489585895868958789588895898959089591895928959389594895958959689597895988959989600896018960289603896048960589606896078960889609896108961189612896138961489615896168961789618896198962089621896228962389624896258962689627896288962989630896318963289633896348963589636896378963889639896408964189642896438964489645896468964789648896498965089651896528965389654896558965689657896588965989660896618966289663896648966589666896678966889669896708967189672896738967489675896768967789678896798968089681896828968389684896858968689687896888968989690896918969289693896948969589696896978969889699897008970189702897038970489705897068970789708897098971089711897128971389714897158971689717897188971989720897218972289723897248972589726897278972889729897308973189732897338973489735897368973789738897398974089741897428974389744897458974689747897488974989750897518975289753897548975589756897578975889759897608976189762897638976489765897668976789768897698977089771897728977389774897758977689777897788977989780897818978289783897848978589786897878978889789897908979189792897938979489795897968979789798897998980089801898028980389804898058980689807898088980989810898118981289813898148981589816898178981889819898208982189822898238982489825898268982789828898298983089831898328983389834898358983689837898388983989840898418984289843898448984589846898478984889849898508985189852898538985489855898568985789858898598986089861898628986389864898658986689867898688986989870898718987289873898748987589876898778987889879898808988189882898838988489885898868988789888898898989089891898928989389894898958989689897898988989989900899018990289903899048990589906899078990889909899108991189912899138991489915899168991789918899198992089921899228992389924899258992689927899288992989930899318993289933899348993589936899378993889939899408994189942899438994489945899468994789948899498995089951899528995389954899558995689957899588995989960899618996289963899648996589966899678996889969899708997189972899738997489975899768997789978899798998089981899828998389984899858998689987899888998989990899918999289993899948999589996899978999889999900009000190002900039000490005900069000790008900099001090011900129001390014900159001690017900189001990020900219002290023900249002590026900279002890029900309003190032900339003490035900369003790038900399004090041900429004390044900459004690047900489004990050900519005290053900549005590056900579005890059900609006190062900639006490065900669006790068900699007090071900729007390074900759007690077900789007990080900819008290083900849008590086900879008890089900909009190092900939009490095900969009790098900999010090101901029010390104901059010690107901089010990110901119011290113901149011590116901179011890119901209012190122901239012490125901269012790128901299013090131901329013390134901359013690137901389013990140901419014290143901449014590146901479014890149901509015190152901539015490155901569015790158901599016090161901629016390164901659016690167901689016990170901719017290173901749017590176901779017890179901809018190182901839018490185901869018790188901899019090191901929019390194901959019690197901989019990200902019020290203902049020590206902079020890209902109021190212902139021490215902169021790218902199022090221902229022390224902259022690227902289022990230902319023290233902349023590236902379023890239902409024190242902439024490245902469024790248902499025090251902529025390254902559025690257902589025990260902619026290263902649026590266902679026890269902709027190272902739027490275902769027790278902799028090281902829028390284902859028690287902889028990290902919029290293902949029590296902979029890299903009030190302903039030490305903069030790308903099031090311903129031390314903159031690317903189031990320903219032290323903249032590326903279032890329903309033190332903339033490335903369033790338903399034090341903429034390344903459034690347903489034990350903519035290353903549035590356903579035890359903609036190362903639036490365903669036790368903699037090371903729037390374903759037690377903789037990380903819038290383903849038590386903879038890389903909039190392903939039490395903969039790398903999040090401904029040390404904059040690407904089040990410904119041290413904149041590416904179041890419904209042190422904239042490425904269042790428904299043090431904329043390434904359043690437904389043990440904419044290443904449044590446904479044890449904509045190452904539045490455904569045790458904599046090461904629046390464904659046690467904689046990470904719047290473904749047590476904779047890479904809048190482904839048490485904869048790488904899049090491904929049390494904959049690497904989049990500905019050290503905049050590506905079050890509905109051190512905139051490515905169051790518905199052090521905229052390524905259052690527905289052990530905319053290533905349053590536905379053890539905409054190542905439054490545905469054790548905499055090551905529055390554905559055690557905589055990560905619056290563905649056590566905679056890569905709057190572905739057490575905769057790578905799058090581905829058390584905859058690587905889058990590905919059290593905949059590596905979059890599906009060190602906039060490605906069060790608906099061090611906129061390614906159061690617906189061990620906219062290623906249062590626906279062890629906309063190632906339063490635906369063790638906399064090641906429064390644906459064690647906489064990650906519065290653906549065590656906579065890659906609066190662906639066490665906669066790668906699067090671906729067390674906759067690677906789067990680906819068290683906849068590686906879068890689906909069190692906939069490695906969069790698906999070090701907029070390704907059070690707907089070990710907119071290713907149071590716907179071890719907209072190722907239072490725907269072790728907299073090731907329073390734907359073690737907389073990740907419074290743907449074590746907479074890749907509075190752907539075490755907569075790758907599076090761907629076390764907659076690767907689076990770907719077290773907749077590776907779077890779907809078190782907839078490785907869078790788907899079090791907929079390794907959079690797907989079990800908019080290803908049080590806908079080890809908109081190812908139081490815908169081790818908199082090821908229082390824908259082690827908289082990830908319083290833908349083590836908379083890839908409084190842908439084490845908469084790848908499085090851908529085390854908559085690857908589085990860908619086290863908649086590866908679086890869908709087190872908739087490875908769087790878908799088090881908829088390884908859088690887908889088990890908919089290893908949089590896908979089890899909009090190902909039090490905909069090790908909099091090911909129091390914909159091690917909189091990920909219092290923909249092590926909279092890929909309093190932909339093490935909369093790938909399094090941909429094390944909459094690947909489094990950909519095290953909549095590956909579095890959909609096190962909639096490965909669096790968909699097090971909729097390974909759097690977909789097990980909819098290983909849098590986909879098890989909909099190992909939099490995909969099790998909999100091001910029100391004910059100691007910089100991010910119101291013910149101591016910179101891019910209102191022910239102491025910269102791028910299103091031910329103391034910359103691037910389103991040910419104291043910449104591046910479104891049910509105191052910539105491055910569105791058910599106091061910629106391064910659106691067910689106991070910719107291073910749107591076910779107891079910809108191082910839108491085910869108791088910899109091091910929109391094910959109691097910989109991100911019110291103911049110591106911079110891109911109111191112911139111491115911169111791118911199112091121911229112391124911259112691127911289112991130911319113291133911349113591136911379113891139911409114191142911439114491145911469114791148911499115091151911529115391154911559115691157911589115991160911619116291163911649116591166911679116891169911709117191172911739117491175911769117791178911799118091181911829118391184911859118691187911889118991190911919119291193911949119591196911979119891199912009120191202912039120491205912069120791208912099121091211912129121391214912159121691217912189121991220912219122291223912249122591226912279122891229912309123191232912339123491235912369123791238912399124091241912429124391244912459124691247912489124991250912519125291253912549125591256912579125891259912609126191262912639126491265912669126791268912699127091271912729127391274912759127691277912789127991280912819128291283912849128591286912879128891289912909129191292912939129491295912969129791298912999130091301913029130391304913059130691307913089130991310913119131291313913149131591316913179131891319913209132191322913239132491325913269132791328913299133091331913329133391334913359133691337913389133991340913419134291343913449134591346913479134891349913509135191352913539135491355913569135791358913599136091361913629136391364913659136691367913689136991370913719137291373913749137591376913779137891379913809138191382913839138491385913869138791388913899139091391913929139391394913959139691397913989139991400914019140291403914049140591406914079140891409914109141191412914139141491415914169141791418914199142091421914229142391424914259142691427914289142991430914319143291433914349143591436914379143891439914409144191442914439144491445914469144791448914499145091451914529145391454914559145691457914589145991460914619146291463914649146591466914679146891469914709147191472914739147491475914769147791478914799148091481914829148391484914859148691487914889148991490914919149291493914949149591496914979149891499915009150191502915039150491505915069150791508915099151091511915129151391514915159151691517915189151991520915219152291523915249152591526915279152891529915309153191532915339153491535915369153791538915399154091541915429154391544915459154691547915489154991550915519155291553915549155591556915579155891559915609156191562915639156491565915669156791568915699157091571915729157391574915759157691577915789157991580915819158291583915849158591586915879158891589915909159191592915939159491595915969159791598915999160091601916029160391604916059160691607916089160991610916119161291613916149161591616916179161891619916209162191622916239162491625916269162791628916299163091631916329163391634916359163691637916389163991640916419164291643916449164591646916479164891649916509165191652916539165491655916569165791658916599166091661916629166391664916659166691667916689166991670916719167291673916749167591676916779167891679916809168191682916839168491685916869168791688916899169091691916929169391694916959169691697916989169991700917019170291703917049170591706917079170891709917109171191712917139171491715917169171791718917199172091721917229172391724917259172691727917289172991730917319173291733917349173591736917379173891739917409174191742917439174491745917469174791748917499175091751917529175391754917559175691757917589175991760917619176291763917649176591766917679176891769917709177191772917739177491775917769177791778917799178091781917829178391784917859178691787917889178991790917919179291793917949179591796917979179891799918009180191802918039180491805918069180791808918099181091811918129181391814918159181691817918189181991820918219182291823918249182591826918279182891829918309183191832918339183491835918369183791838918399184091841918429184391844918459184691847918489184991850918519185291853918549185591856918579185891859918609186191862918639186491865918669186791868918699187091871918729187391874918759187691877918789187991880918819188291883918849188591886918879188891889918909189191892918939189491895918969189791898918999190091901919029190391904919059190691907919089190991910919119191291913919149191591916919179191891919919209192191922919239192491925919269192791928919299193091931919329193391934919359193691937919389193991940919419194291943919449194591946919479194891949919509195191952919539195491955919569195791958919599196091961919629196391964919659196691967919689196991970919719197291973919749197591976919779197891979919809198191982919839198491985919869198791988919899199091991919929199391994919959199691997919989199992000920019200292003920049200592006920079200892009920109201192012920139201492015920169201792018920199202092021920229202392024920259202692027920289202992030920319203292033920349203592036920379203892039920409204192042920439204492045920469204792048920499205092051920529205392054920559205692057920589205992060920619206292063920649206592066920679206892069920709207192072920739207492075920769207792078920799208092081920829208392084920859208692087920889208992090920919209292093920949209592096920979209892099921009210192102921039210492105921069210792108921099211092111921129211392114921159211692117921189211992120921219212292123921249212592126921279212892129921309213192132921339213492135921369213792138921399214092141921429214392144921459214692147921489214992150921519215292153921549215592156921579215892159921609216192162921639216492165921669216792168921699217092171921729217392174921759217692177921789217992180921819218292183921849218592186921879218892189921909219192192921939219492195921969219792198921999220092201922029220392204922059220692207922089220992210922119221292213922149221592216922179221892219922209222192222922239222492225922269222792228922299223092231922329223392234922359223692237922389223992240922419224292243922449224592246922479224892249922509225192252922539225492255922569225792258922599226092261922629226392264922659226692267922689226992270922719227292273922749227592276922779227892279922809228192282922839228492285922869228792288922899229092291922929229392294922959229692297922989229992300923019230292303923049230592306923079230892309923109231192312923139231492315923169231792318923199232092321923229232392324923259232692327923289232992330923319233292333923349233592336923379233892339923409234192342923439234492345923469234792348923499235092351923529235392354923559235692357923589235992360923619236292363923649236592366923679236892369923709237192372923739237492375923769237792378923799238092381923829238392384923859238692387923889238992390923919239292393923949239592396923979239892399924009240192402924039240492405924069240792408924099241092411924129241392414924159241692417924189241992420924219242292423924249242592426924279242892429924309243192432924339243492435924369243792438924399244092441924429244392444924459244692447924489244992450924519245292453924549245592456924579245892459924609246192462924639246492465924669246792468924699247092471924729247392474924759247692477924789247992480924819248292483924849248592486924879248892489924909249192492924939249492495924969249792498924999250092501925029250392504925059250692507925089250992510925119251292513925149251592516925179251892519925209252192522925239252492525925269252792528925299253092531925329253392534925359253692537925389253992540925419254292543925449254592546925479254892549925509255192552925539255492555925569255792558925599256092561925629256392564925659256692567925689256992570925719257292573925749257592576925779257892579925809258192582925839258492585925869258792588925899259092591925929259392594925959259692597925989259992600926019260292603926049260592606926079260892609926109261192612926139261492615926169261792618926199262092621926229262392624926259262692627926289262992630926319263292633926349263592636926379263892639926409264192642926439264492645926469264792648926499265092651926529265392654926559265692657926589265992660926619266292663926649266592666926679266892669926709267192672926739267492675926769267792678926799268092681926829268392684926859268692687926889268992690926919269292693926949269592696926979269892699927009270192702927039270492705927069270792708927099271092711927129271392714927159271692717927189271992720927219272292723927249272592726927279272892729927309273192732927339273492735927369273792738927399274092741927429274392744927459274692747927489274992750927519275292753927549275592756927579275892759927609276192762927639276492765927669276792768927699277092771927729277392774927759277692777927789277992780927819278292783927849278592786927879278892789927909279192792927939279492795927969279792798927999280092801928029280392804928059280692807928089280992810928119281292813928149281592816928179281892819928209282192822928239282492825928269282792828928299283092831928329283392834928359283692837928389283992840928419284292843928449284592846928479284892849928509285192852928539285492855928569285792858928599286092861928629286392864928659286692867928689286992870928719287292873928749287592876928779287892879928809288192882928839288492885928869288792888928899289092891928929289392894928959289692897928989289992900929019290292903929049290592906929079290892909929109291192912929139291492915929169291792918929199292092921929229292392924929259292692927929289292992930929319293292933929349293592936929379293892939929409294192942929439294492945929469294792948929499295092951929529295392954929559295692957929589295992960929619296292963929649296592966929679296892969929709297192972929739297492975929769297792978929799298092981929829298392984929859298692987929889298992990929919299292993929949299592996929979299892999930009300193002
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || (function () {
  8. var extendStatics = Object.setPrototypeOf ||
  9. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  10. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  11. return function (d, b) {
  12. extendStatics(d, b);
  13. function __() { this.constructor = d; }
  14. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  15. };
  16. })();
  17. (function universalModuleDefinition(root, factory) {
  18. if(typeof exports === 'object' && typeof module === 'object')
  19. module.exports = factory();
  20. else if(typeof define === 'function' && define.amd)
  21. define("babylonjs", [], factory);
  22. else if(typeof exports === 'object')
  23. exports["babylonjs"] = factory();
  24. else {
  25. root["BABYLON"] = factory(root["BABYLON"]);
  26. }
  27. })(this, function() {
  28. "use strict";
  29. var BABYLON;
  30. (function (BABYLON) {
  31. /**
  32. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  33. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  34. */
  35. var EffectFallbacks = /** @class */ (function () {
  36. function EffectFallbacks() {
  37. this._defines = {};
  38. this._currentRank = 32;
  39. this._maxRank = -1;
  40. }
  41. /**
  42. * Removes the fallback from the bound mesh.
  43. */
  44. EffectFallbacks.prototype.unBindMesh = function () {
  45. this._mesh = null;
  46. };
  47. /**
  48. * Adds a fallback on the specified property.
  49. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  50. * @param define The name of the define in the shader
  51. */
  52. EffectFallbacks.prototype.addFallback = function (rank, define) {
  53. if (!this._defines[rank]) {
  54. if (rank < this._currentRank) {
  55. this._currentRank = rank;
  56. }
  57. if (rank > this._maxRank) {
  58. this._maxRank = rank;
  59. }
  60. this._defines[rank] = new Array();
  61. }
  62. this._defines[rank].push(define);
  63. };
  64. /**
  65. * Sets the mesh to use CPU skinning when needing to fallback.
  66. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  67. * @param mesh The mesh to use the fallbacks.
  68. */
  69. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  70. this._mesh = mesh;
  71. if (rank < this._currentRank) {
  72. this._currentRank = rank;
  73. }
  74. if (rank > this._maxRank) {
  75. this._maxRank = rank;
  76. }
  77. };
  78. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  79. /**
  80. * Checks to see if more fallbacks are still availible.
  81. */
  82. get: function () {
  83. return this._currentRank <= this._maxRank;
  84. },
  85. enumerable: true,
  86. configurable: true
  87. });
  88. /**
  89. * Removes the defines that shoould be removed when falling back.
  90. * @param currentDefines defines the current define statements for the shader.
  91. * @param effect defines the current effect we try to compile
  92. * @returns The resulting defines with defines of the current rank removed.
  93. */
  94. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  95. // First we try to switch to CPU skinning
  96. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  97. this._mesh.computeBonesUsingShaders = false;
  98. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  99. var scene = this._mesh.getScene();
  100. for (var index = 0; index < scene.meshes.length; index++) {
  101. var otherMesh = scene.meshes[index];
  102. if (!otherMesh.material) {
  103. continue;
  104. }
  105. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  106. continue;
  107. }
  108. if (otherMesh.material.getEffect() === effect) {
  109. otherMesh.computeBonesUsingShaders = false;
  110. }
  111. else {
  112. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  113. var subMesh = _a[_i];
  114. var subMeshEffect = subMesh.effect;
  115. if (subMeshEffect === effect) {
  116. otherMesh.computeBonesUsingShaders = false;
  117. break;
  118. }
  119. }
  120. }
  121. }
  122. }
  123. else {
  124. var currentFallbacks = this._defines[this._currentRank];
  125. if (currentFallbacks) {
  126. for (var index = 0; index < currentFallbacks.length; index++) {
  127. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  128. }
  129. }
  130. this._currentRank++;
  131. }
  132. return currentDefines;
  133. };
  134. return EffectFallbacks;
  135. }());
  136. BABYLON.EffectFallbacks = EffectFallbacks;
  137. /**
  138. * Options to be used when creating an effect.
  139. */
  140. var EffectCreationOptions = /** @class */ (function () {
  141. function EffectCreationOptions() {
  142. }
  143. return EffectCreationOptions;
  144. }());
  145. BABYLON.EffectCreationOptions = EffectCreationOptions;
  146. /**
  147. * Effect containing vertex and fragment shader that can be executed on an object.
  148. */
  149. var Effect = /** @class */ (function () {
  150. /**
  151. * Instantiates an effect.
  152. * An effect can be used to create/manage/execute vertex and fragment shaders.
  153. * @param baseName Name of the effect.
  154. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  155. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  156. * @param samplers List of sampler variables that will be passed to the shader.
  157. * @param engine Engine to be used to render the effect
  158. * @param defines Define statements to be added to the shader.
  159. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  160. * @param onCompiled Callback that will be called when the shader is compiled.
  161. * @param onError Callback that will be called if an error occurs during shader compilation.
  162. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  163. */
  164. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  165. if (samplers === void 0) { samplers = null; }
  166. if (defines === void 0) { defines = null; }
  167. if (fallbacks === void 0) { fallbacks = null; }
  168. if (onCompiled === void 0) { onCompiled = null; }
  169. if (onError === void 0) { onError = null; }
  170. var _this = this;
  171. /**
  172. * Unique ID of the effect.
  173. */
  174. this.uniqueId = 0;
  175. /**
  176. * Observable that will be called when the shader is compiled.
  177. */
  178. this.onCompileObservable = new BABYLON.Observable();
  179. /**
  180. * Observable that will be called if an error occurs during shader compilation.
  181. */
  182. this.onErrorObservable = new BABYLON.Observable();
  183. /**
  184. * Observable that will be called when effect is bound.
  185. */
  186. this.onBindObservable = new BABYLON.Observable();
  187. this._uniformBuffersNames = {};
  188. this._isReady = false;
  189. this._compilationError = "";
  190. this.name = baseName;
  191. if (attributesNamesOrOptions.attributes) {
  192. var options = attributesNamesOrOptions;
  193. this._engine = uniformsNamesOrEngine;
  194. this._attributesNames = options.attributes;
  195. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  196. this._samplers = options.samplers;
  197. this.defines = options.defines;
  198. this.onError = options.onError;
  199. this.onCompiled = options.onCompiled;
  200. this._fallbacks = options.fallbacks;
  201. this._indexParameters = options.indexParameters;
  202. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  203. if (options.uniformBuffersNames) {
  204. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  205. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  206. }
  207. }
  208. }
  209. else {
  210. this._engine = engine;
  211. this.defines = defines;
  212. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  213. this._samplers = samplers;
  214. this._attributesNames = attributesNamesOrOptions;
  215. this.onError = onError;
  216. this.onCompiled = onCompiled;
  217. this._indexParameters = indexParameters;
  218. this._fallbacks = fallbacks;
  219. }
  220. this.uniqueId = Effect._uniqueIdSeed++;
  221. if (this._getFromCache(baseName)) {
  222. this._prepareEffect();
  223. return;
  224. }
  225. var vertexSource;
  226. var fragmentSource;
  227. if (baseName.vertexElement) {
  228. vertexSource = document.getElementById(baseName.vertexElement);
  229. if (!vertexSource) {
  230. vertexSource = baseName.vertexElement;
  231. }
  232. }
  233. else {
  234. vertexSource = baseName.vertex || baseName;
  235. }
  236. if (baseName.fragmentElement) {
  237. fragmentSource = document.getElementById(baseName.fragmentElement);
  238. if (!fragmentSource) {
  239. fragmentSource = baseName.fragmentElement;
  240. }
  241. }
  242. else {
  243. fragmentSource = baseName.fragment || baseName;
  244. }
  245. var finalVertexCode;
  246. this._loadVertexShaderAsync(vertexSource)
  247. .then(function (vertexCode) {
  248. return _this._processIncludesAsync(vertexCode);
  249. })
  250. .then(function (vertexCodeWithIncludes) {
  251. finalVertexCode = _this._processShaderConversion(vertexCodeWithIncludes, false);
  252. return _this._loadFragmentShaderAsync(fragmentSource);
  253. })
  254. .then(function (fragmentCode) {
  255. return _this._processIncludesAsync(fragmentCode);
  256. })
  257. .then(function (fragmentCodeWithIncludes) {
  258. var migratedFragmentCode = _this._processShaderConversion(fragmentCodeWithIncludes, true);
  259. if (baseName) {
  260. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  261. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  262. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + finalVertexCode;
  263. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  264. }
  265. else {
  266. _this._vertexSourceCode = finalVertexCode;
  267. _this._fragmentSourceCode = migratedFragmentCode;
  268. }
  269. _this._setInCache(baseName);
  270. _this._prepareEffect();
  271. });
  272. }
  273. Effect.prototype._getSourceCacheKey = function (baseName) {
  274. var cacheKey = baseName;
  275. if (this._indexParameters) {
  276. for (var key in this._indexParameters) {
  277. if (this._indexParameters.hasOwnProperty(key)) {
  278. cacheKey += "|";
  279. cacheKey += key;
  280. cacheKey += "_";
  281. cacheKey += this._indexParameters[key];
  282. }
  283. }
  284. }
  285. return cacheKey;
  286. };
  287. Effect.prototype._getFromCache = function (baseName) {
  288. if (typeof baseName !== "string") {
  289. return false;
  290. }
  291. var cacheKey = this._getSourceCacheKey(baseName);
  292. var sources = Effect._sourceCache[cacheKey];
  293. if (!sources) {
  294. return false;
  295. }
  296. this._vertexSourceCode = sources.vertex;
  297. this._fragmentSourceCode = sources.fragment;
  298. return true;
  299. };
  300. Effect.prototype._setInCache = function (baseName) {
  301. if (typeof baseName !== "string") {
  302. return;
  303. }
  304. var cacheKey = this._getSourceCacheKey(baseName);
  305. Effect._sourceCache[cacheKey] = {
  306. vertex: this._vertexSourceCode,
  307. fragment: this._fragmentSourceCode
  308. };
  309. };
  310. Object.defineProperty(Effect.prototype, "key", {
  311. /**
  312. * Unique key for this effect
  313. */
  314. get: function () {
  315. return this._key;
  316. },
  317. enumerable: true,
  318. configurable: true
  319. });
  320. /**
  321. * If the effect has been compiled and prepared.
  322. * @returns if the effect is compiled and prepared.
  323. */
  324. Effect.prototype.isReady = function () {
  325. return this._isReady;
  326. };
  327. /**
  328. * The engine the effect was initialized with.
  329. * @returns the engine.
  330. */
  331. Effect.prototype.getEngine = function () {
  332. return this._engine;
  333. };
  334. /**
  335. * The compiled webGL program for the effect
  336. * @returns the webGL program.
  337. */
  338. Effect.prototype.getProgram = function () {
  339. return this._program;
  340. };
  341. /**
  342. * The set of names of attribute variables for the shader.
  343. * @returns An array of attribute names.
  344. */
  345. Effect.prototype.getAttributesNames = function () {
  346. return this._attributesNames;
  347. };
  348. /**
  349. * Returns the attribute at the given index.
  350. * @param index The index of the attribute.
  351. * @returns The location of the attribute.
  352. */
  353. Effect.prototype.getAttributeLocation = function (index) {
  354. return this._attributes[index];
  355. };
  356. /**
  357. * Returns the attribute based on the name of the variable.
  358. * @param name of the attribute to look up.
  359. * @returns the attribute location.
  360. */
  361. Effect.prototype.getAttributeLocationByName = function (name) {
  362. var index = this._attributesNames.indexOf(name);
  363. return this._attributes[index];
  364. };
  365. /**
  366. * The number of attributes.
  367. * @returns the numnber of attributes.
  368. */
  369. Effect.prototype.getAttributesCount = function () {
  370. return this._attributes.length;
  371. };
  372. /**
  373. * Gets the index of a uniform variable.
  374. * @param uniformName of the uniform to look up.
  375. * @returns the index.
  376. */
  377. Effect.prototype.getUniformIndex = function (uniformName) {
  378. return this._uniformsNames.indexOf(uniformName);
  379. };
  380. /**
  381. * Returns the attribute based on the name of the variable.
  382. * @param uniformName of the uniform to look up.
  383. * @returns the location of the uniform.
  384. */
  385. Effect.prototype.getUniform = function (uniformName) {
  386. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  387. };
  388. /**
  389. * Returns an array of sampler variable names
  390. * @returns The array of sampler variable neames.
  391. */
  392. Effect.prototype.getSamplers = function () {
  393. return this._samplers;
  394. };
  395. /**
  396. * The error from the last compilation.
  397. * @returns the error string.
  398. */
  399. Effect.prototype.getCompilationError = function () {
  400. return this._compilationError;
  401. };
  402. /**
  403. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  404. * @param func The callback to be used.
  405. */
  406. Effect.prototype.executeWhenCompiled = function (func) {
  407. if (this.isReady()) {
  408. func(this);
  409. return;
  410. }
  411. this.onCompileObservable.add(function (effect) {
  412. func(effect);
  413. });
  414. };
  415. /** @ignore */
  416. Effect.prototype._loadVertexShaderAsync = function (vertex) {
  417. if (BABYLON.Tools.IsWindowObjectExist()) {
  418. // DOM element ?
  419. if (vertex instanceof HTMLElement) {
  420. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  421. return Promise.resolve(vertexCode);
  422. }
  423. }
  424. // Base64 encoded ?
  425. if (vertex.substr(0, 7) === "base64:") {
  426. var vertexBinary = window.atob(vertex.substr(7));
  427. return Promise.resolve(vertexBinary);
  428. }
  429. // Is in local store ?
  430. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  431. return Promise.resolve(Effect.ShadersStore[vertex + "VertexShader"]);
  432. }
  433. var vertexShaderUrl;
  434. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  435. vertexShaderUrl = vertex;
  436. }
  437. else {
  438. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  439. }
  440. // Vertex shader
  441. return this._engine._loadFileAsync(vertexShaderUrl + ".vertex.fx");
  442. };
  443. /** @ignore */
  444. Effect.prototype._loadFragmentShaderAsync = function (fragment) {
  445. if (BABYLON.Tools.IsWindowObjectExist()) {
  446. // DOM element ?
  447. if (fragment instanceof HTMLElement) {
  448. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  449. return Promise.resolve(fragmentCode);
  450. }
  451. }
  452. // Base64 encoded ?
  453. if (fragment.substr(0, 7) === "base64:") {
  454. var fragmentBinary = window.atob(fragment.substr(7));
  455. return Promise.resolve(fragmentBinary);
  456. }
  457. // Is in local store ?
  458. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  459. return Promise.resolve(Effect.ShadersStore[fragment + "PixelShader"]);
  460. }
  461. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  462. return Promise.resolve(Effect.ShadersStore[fragment + "FragmentShader"]);
  463. }
  464. var fragmentShaderUrl;
  465. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  466. fragmentShaderUrl = fragment;
  467. }
  468. else {
  469. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  470. }
  471. // Fragment shader
  472. return this._engine._loadFileAsync(fragmentShaderUrl + ".fragment.fx");
  473. };
  474. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  475. // Rebuild shaders source code
  476. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  477. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  478. vertexCode = prefix + vertexCode;
  479. fragmentCode = prefix + fragmentCode;
  480. // Number lines of shaders source code
  481. var i = 2;
  482. var regex = /\n/gm;
  483. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  484. i = 2;
  485. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  486. // Dump shaders name and formatted source code
  487. if (this.name.vertexElement) {
  488. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  489. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  490. }
  491. else if (this.name.vertex) {
  492. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  493. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  494. }
  495. else {
  496. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  497. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  498. }
  499. };
  500. ;
  501. Effect.prototype._processShaderConversion = function (sourceCode, isFragment) {
  502. var preparedSourceCode = this._processPrecision(sourceCode);
  503. if (this._engine.webGLVersion == 1) {
  504. return preparedSourceCode;
  505. }
  506. // Already converted
  507. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  508. return preparedSourceCode.replace("#version 300 es", "");
  509. }
  510. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  511. // Remove extensions
  512. // #extension GL_OES_standard_derivatives : enable
  513. // #extension GL_EXT_shader_texture_lod : enable
  514. // #extension GL_EXT_frag_depth : enable
  515. // #extension GL_EXT_draw_buffers : require
  516. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  517. var result = preparedSourceCode.replace(regex, "");
  518. // Migrate to GLSL v300
  519. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  520. result = result.replace(/attribute[ \t]/g, "in ");
  521. result = result.replace(/[ \t]attribute/g, " in");
  522. if (isFragment) {
  523. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  524. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  525. result = result.replace(/texture2D\s*\(/g, "texture(");
  526. result = result.replace(/textureCube\s*\(/g, "texture(");
  527. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  528. result = result.replace(/gl_FragColor/g, "glFragColor");
  529. result = result.replace(/gl_FragData/g, "glFragData");
  530. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  531. }
  532. return result;
  533. };
  534. Effect.prototype._processIncludesAsync = function (sourceCode) {
  535. var _this = this;
  536. return new Promise(function (resolve, reject) {
  537. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  538. var match = regex.exec(sourceCode);
  539. var returnValue = sourceCode;
  540. while (match != null) {
  541. var includeFile = match[1];
  542. // Uniform declaration
  543. if (includeFile.indexOf("__decl__") !== -1) {
  544. includeFile = includeFile.replace(/__decl__/, "");
  545. if (_this._engine.supportsUniformBuffers) {
  546. includeFile = includeFile.replace(/Vertex/, "Ubo");
  547. includeFile = includeFile.replace(/Fragment/, "Ubo");
  548. }
  549. includeFile = includeFile + "Declaration";
  550. }
  551. if (Effect.IncludesShadersStore[includeFile]) {
  552. // Substitution
  553. var includeContent = Effect.IncludesShadersStore[includeFile];
  554. if (match[2]) {
  555. var splits = match[3].split(",");
  556. for (var index = 0; index < splits.length; index += 2) {
  557. var source = new RegExp(splits[index], "g");
  558. var dest = splits[index + 1];
  559. includeContent = includeContent.replace(source, dest);
  560. }
  561. }
  562. if (match[4]) {
  563. var indexString = match[5];
  564. if (indexString.indexOf("..") !== -1) {
  565. var indexSplits = indexString.split("..");
  566. var minIndex = parseInt(indexSplits[0]);
  567. var maxIndex = parseInt(indexSplits[1]);
  568. var sourceIncludeContent = includeContent.slice(0);
  569. includeContent = "";
  570. if (isNaN(maxIndex)) {
  571. maxIndex = _this._indexParameters[indexSplits[1]];
  572. }
  573. for (var i = minIndex; i < maxIndex; i++) {
  574. if (!_this._engine.supportsUniformBuffers) {
  575. // Ubo replacement
  576. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  577. return p1 + "{X}";
  578. });
  579. }
  580. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  581. }
  582. }
  583. else {
  584. if (!_this._engine.supportsUniformBuffers) {
  585. // Ubo replacement
  586. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  587. return p1 + "{X}";
  588. });
  589. }
  590. includeContent = includeContent.replace(/\{X\}/g, indexString);
  591. }
  592. }
  593. // Replace
  594. returnValue = returnValue.replace(match[0], includeContent);
  595. }
  596. else {
  597. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  598. _this._engine._loadFileAsync(includeShaderUrl)
  599. .then(function (fileContent) {
  600. Effect.IncludesShadersStore[includeFile] = fileContent;
  601. return _this._processIncludesAsync(returnValue);
  602. })
  603. .then(function (returnValue) {
  604. resolve(returnValue);
  605. });
  606. return;
  607. }
  608. match = regex.exec(sourceCode);
  609. }
  610. resolve(returnValue);
  611. });
  612. };
  613. Effect.prototype._processPrecision = function (source) {
  614. if (source.indexOf("precision highp float") === -1) {
  615. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  616. source = "precision mediump float;\n" + source;
  617. }
  618. else {
  619. source = "precision highp float;\n" + source;
  620. }
  621. }
  622. else {
  623. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  624. source = source.replace("precision highp float", "precision mediump float");
  625. }
  626. }
  627. return source;
  628. };
  629. /**
  630. * Recompiles the webGL program
  631. * @param vertexSourceCode The source code for the vertex shader.
  632. * @param fragmentSourceCode The source code for the fragment shader.
  633. * @param onCompiled Callback called when completed.
  634. * @param onError Callback called on error.
  635. */
  636. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  637. var _this = this;
  638. this._isReady = false;
  639. this._vertexSourceCodeOverride = vertexSourceCode;
  640. this._fragmentSourceCodeOverride = fragmentSourceCode;
  641. this.onError = function (effect, error) {
  642. if (onError) {
  643. onError(error);
  644. }
  645. };
  646. this.onCompiled = function () {
  647. var scenes = _this.getEngine().scenes;
  648. for (var i = 0; i < scenes.length; i++) {
  649. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  650. }
  651. if (onCompiled) {
  652. onCompiled(_this._program);
  653. }
  654. };
  655. this._fallbacks = null;
  656. this._prepareEffect();
  657. };
  658. /**
  659. * Gets the uniform locations of the the specified variable names
  660. * @param names THe names of the variables to lookup.
  661. * @returns Array of locations in the same order as variable names.
  662. */
  663. Effect.prototype.getSpecificUniformLocations = function (names) {
  664. var engine = this._engine;
  665. return engine.getUniforms(this._program, names);
  666. };
  667. /**
  668. * Prepares the effect
  669. */
  670. Effect.prototype._prepareEffect = function () {
  671. var attributesNames = this._attributesNames;
  672. var defines = this.defines;
  673. var fallbacks = this._fallbacks;
  674. this._valueCache = {};
  675. var previousProgram = this._program;
  676. try {
  677. var engine = this._engine;
  678. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  679. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  680. }
  681. else {
  682. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  683. }
  684. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  685. if (engine.supportsUniformBuffers) {
  686. for (var name in this._uniformBuffersNames) {
  687. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  688. }
  689. }
  690. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  691. this._attributes = engine.getAttributes(this._program, attributesNames);
  692. var index;
  693. for (index = 0; index < this._samplers.length; index++) {
  694. var sampler = this.getUniform(this._samplers[index]);
  695. if (sampler == null) {
  696. this._samplers.splice(index, 1);
  697. index--;
  698. }
  699. }
  700. engine.bindSamplers(this);
  701. this._compilationError = "";
  702. this._isReady = true;
  703. if (this.onCompiled) {
  704. this.onCompiled(this);
  705. }
  706. this.onCompileObservable.notifyObservers(this);
  707. this.onCompileObservable.clear();
  708. // Unbind mesh reference in fallbacks
  709. if (this._fallbacks) {
  710. this._fallbacks.unBindMesh();
  711. }
  712. if (previousProgram) {
  713. this.getEngine()._deleteProgram(previousProgram);
  714. }
  715. }
  716. catch (e) {
  717. this._compilationError = e.message;
  718. // Let's go through fallbacks then
  719. BABYLON.Tools.Error("Unable to compile effect:");
  720. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  721. return " " + uniform;
  722. }));
  723. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  724. return " " + attribute;
  725. }));
  726. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  727. BABYLON.Tools.Error("Error: " + this._compilationError);
  728. if (previousProgram) {
  729. this._program = previousProgram;
  730. this._isReady = true;
  731. if (this.onError) {
  732. this.onError(this, this._compilationError);
  733. }
  734. this.onErrorObservable.notifyObservers(this);
  735. }
  736. if (fallbacks && fallbacks.isMoreFallbacks) {
  737. BABYLON.Tools.Error("Trying next fallback.");
  738. this.defines = fallbacks.reduce(this.defines, this);
  739. this._prepareEffect();
  740. }
  741. else {
  742. if (this.onError) {
  743. this.onError(this, this._compilationError);
  744. }
  745. this.onErrorObservable.notifyObservers(this);
  746. this.onErrorObservable.clear();
  747. // Unbind mesh reference in fallbacks
  748. if (this._fallbacks) {
  749. this._fallbacks.unBindMesh();
  750. }
  751. }
  752. }
  753. };
  754. Object.defineProperty(Effect.prototype, "isSupported", {
  755. /**
  756. * Checks if the effect is supported. (Must be called after compilation)
  757. */
  758. get: function () {
  759. return this._compilationError === "";
  760. },
  761. enumerable: true,
  762. configurable: true
  763. });
  764. /**
  765. * Binds a texture to the engine to be used as output of the shader.
  766. * @param channel Name of the output variable.
  767. * @param texture Texture to bind.
  768. */
  769. Effect.prototype._bindTexture = function (channel, texture) {
  770. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  771. };
  772. /**
  773. * Sets a texture on the engine to be used in the shader.
  774. * @param channel Name of the sampler variable.
  775. * @param texture Texture to set.
  776. */
  777. Effect.prototype.setTexture = function (channel, texture) {
  778. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  779. };
  780. /**
  781. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  782. * @param channel Name of the sampler variable.
  783. * @param texture Texture to set.
  784. */
  785. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  786. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  787. };
  788. /**
  789. * Sets an array of textures on the engine to be used in the shader.
  790. * @param channel Name of the variable.
  791. * @param textures Textures to set.
  792. */
  793. Effect.prototype.setTextureArray = function (channel, textures) {
  794. if (this._samplers.indexOf(channel + "Ex") === -1) {
  795. var initialPos = this._samplers.indexOf(channel);
  796. for (var index = 1; index < textures.length; index++) {
  797. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  798. }
  799. }
  800. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  801. };
  802. /**
  803. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  804. * 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)
  805. * @param channel Name of the sampler variable.
  806. * @param postProcess Post process to get the input texture from.
  807. */
  808. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  809. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  810. };
  811. /**
  812. * Sets the output texture of the passed in post process to be input of this effect.
  813. * @param channel Name of the sampler variable.
  814. * @param postProcess Post process to get the output texture from.
  815. */
  816. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  817. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  818. };
  819. /** @ignore */
  820. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  821. var cache = this._valueCache[uniformName];
  822. var flag = matrix.updateFlag;
  823. if (cache !== undefined && cache === flag) {
  824. return false;
  825. }
  826. this._valueCache[uniformName] = flag;
  827. return true;
  828. };
  829. /** @ignore */
  830. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  831. var cache = this._valueCache[uniformName];
  832. if (!cache) {
  833. cache = [x, y];
  834. this._valueCache[uniformName] = cache;
  835. return true;
  836. }
  837. var changed = false;
  838. if (cache[0] !== x) {
  839. cache[0] = x;
  840. changed = true;
  841. }
  842. if (cache[1] !== y) {
  843. cache[1] = y;
  844. changed = true;
  845. }
  846. return changed;
  847. };
  848. /** @ignore */
  849. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  850. var cache = this._valueCache[uniformName];
  851. if (!cache) {
  852. cache = [x, y, z];
  853. this._valueCache[uniformName] = cache;
  854. return true;
  855. }
  856. var changed = false;
  857. if (cache[0] !== x) {
  858. cache[0] = x;
  859. changed = true;
  860. }
  861. if (cache[1] !== y) {
  862. cache[1] = y;
  863. changed = true;
  864. }
  865. if (cache[2] !== z) {
  866. cache[2] = z;
  867. changed = true;
  868. }
  869. return changed;
  870. };
  871. /** @ignore */
  872. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  873. var cache = this._valueCache[uniformName];
  874. if (!cache) {
  875. cache = [x, y, z, w];
  876. this._valueCache[uniformName] = cache;
  877. return true;
  878. }
  879. var changed = false;
  880. if (cache[0] !== x) {
  881. cache[0] = x;
  882. changed = true;
  883. }
  884. if (cache[1] !== y) {
  885. cache[1] = y;
  886. changed = true;
  887. }
  888. if (cache[2] !== z) {
  889. cache[2] = z;
  890. changed = true;
  891. }
  892. if (cache[3] !== w) {
  893. cache[3] = w;
  894. changed = true;
  895. }
  896. return changed;
  897. };
  898. /**
  899. * Binds a buffer to a uniform.
  900. * @param buffer Buffer to bind.
  901. * @param name Name of the uniform variable to bind to.
  902. */
  903. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  904. var bufferName = this._uniformBuffersNames[name];
  905. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  906. return;
  907. }
  908. Effect._baseCache[bufferName] = buffer;
  909. this._engine.bindUniformBufferBase(buffer, bufferName);
  910. };
  911. /**
  912. * Binds block to a uniform.
  913. * @param blockName Name of the block to bind.
  914. * @param index Index to bind.
  915. */
  916. Effect.prototype.bindUniformBlock = function (blockName, index) {
  917. this._engine.bindUniformBlock(this._program, blockName, index);
  918. };
  919. /**
  920. * Sets an interger value on a uniform variable.
  921. * @param uniformName Name of the variable.
  922. * @param value Value to be set.
  923. * @returns this effect.
  924. */
  925. Effect.prototype.setInt = function (uniformName, value) {
  926. var cache = this._valueCache[uniformName];
  927. if (cache !== undefined && cache === value)
  928. return this;
  929. this._valueCache[uniformName] = value;
  930. this._engine.setInt(this.getUniform(uniformName), value);
  931. return this;
  932. };
  933. /**
  934. * Sets an int array on a uniform variable.
  935. * @param uniformName Name of the variable.
  936. * @param array array to be set.
  937. * @returns this effect.
  938. */
  939. Effect.prototype.setIntArray = function (uniformName, array) {
  940. this._valueCache[uniformName] = null;
  941. this._engine.setIntArray(this.getUniform(uniformName), array);
  942. return this;
  943. };
  944. /**
  945. * 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)
  946. * @param uniformName Name of the variable.
  947. * @param array array to be set.
  948. * @returns this effect.
  949. */
  950. Effect.prototype.setIntArray2 = function (uniformName, array) {
  951. this._valueCache[uniformName] = null;
  952. this._engine.setIntArray2(this.getUniform(uniformName), array);
  953. return this;
  954. };
  955. /**
  956. * 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)
  957. * @param uniformName Name of the variable.
  958. * @param array array to be set.
  959. * @returns this effect.
  960. */
  961. Effect.prototype.setIntArray3 = function (uniformName, array) {
  962. this._valueCache[uniformName] = null;
  963. this._engine.setIntArray3(this.getUniform(uniformName), array);
  964. return this;
  965. };
  966. /**
  967. * 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)
  968. * @param uniformName Name of the variable.
  969. * @param array array to be set.
  970. * @returns this effect.
  971. */
  972. Effect.prototype.setIntArray4 = function (uniformName, array) {
  973. this._valueCache[uniformName] = null;
  974. this._engine.setIntArray4(this.getUniform(uniformName), array);
  975. return this;
  976. };
  977. /**
  978. * Sets an float array on a uniform variable.
  979. * @param uniformName Name of the variable.
  980. * @param array array to be set.
  981. * @returns this effect.
  982. */
  983. Effect.prototype.setFloatArray = function (uniformName, array) {
  984. this._valueCache[uniformName] = null;
  985. this._engine.setFloatArray(this.getUniform(uniformName), array);
  986. return this;
  987. };
  988. /**
  989. * 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)
  990. * @param uniformName Name of the variable.
  991. * @param array array to be set.
  992. * @returns this effect.
  993. */
  994. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  995. this._valueCache[uniformName] = null;
  996. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  997. return this;
  998. };
  999. /**
  1000. * 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)
  1001. * @param uniformName Name of the variable.
  1002. * @param array array to be set.
  1003. * @returns this effect.
  1004. */
  1005. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  1006. this._valueCache[uniformName] = null;
  1007. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  1008. return this;
  1009. };
  1010. /**
  1011. * 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)
  1012. * @param uniformName Name of the variable.
  1013. * @param array array to be set.
  1014. * @returns this effect.
  1015. */
  1016. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  1017. this._valueCache[uniformName] = null;
  1018. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  1019. return this;
  1020. };
  1021. /**
  1022. * Sets an array on a uniform variable.
  1023. * @param uniformName Name of the variable.
  1024. * @param array array to be set.
  1025. * @returns this effect.
  1026. */
  1027. Effect.prototype.setArray = function (uniformName, array) {
  1028. this._valueCache[uniformName] = null;
  1029. this._engine.setArray(this.getUniform(uniformName), array);
  1030. return this;
  1031. };
  1032. /**
  1033. * 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)
  1034. * @param uniformName Name of the variable.
  1035. * @param array array to be set.
  1036. * @returns this effect.
  1037. */
  1038. Effect.prototype.setArray2 = function (uniformName, array) {
  1039. this._valueCache[uniformName] = null;
  1040. this._engine.setArray2(this.getUniform(uniformName), array);
  1041. return this;
  1042. };
  1043. /**
  1044. * 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)
  1045. * @param uniformName Name of the variable.
  1046. * @param array array to be set.
  1047. * @returns this effect.
  1048. */
  1049. Effect.prototype.setArray3 = function (uniformName, array) {
  1050. this._valueCache[uniformName] = null;
  1051. this._engine.setArray3(this.getUniform(uniformName), array);
  1052. return this;
  1053. };
  1054. /**
  1055. * 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)
  1056. * @param uniformName Name of the variable.
  1057. * @param array array to be set.
  1058. * @returns this effect.
  1059. */
  1060. Effect.prototype.setArray4 = function (uniformName, array) {
  1061. this._valueCache[uniformName] = null;
  1062. this._engine.setArray4(this.getUniform(uniformName), array);
  1063. return this;
  1064. };
  1065. /**
  1066. * Sets matrices on a uniform variable.
  1067. * @param uniformName Name of the variable.
  1068. * @param matrices matrices to be set.
  1069. * @returns this effect.
  1070. */
  1071. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1072. if (!matrices) {
  1073. return this;
  1074. }
  1075. this._valueCache[uniformName] = null;
  1076. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1077. return this;
  1078. };
  1079. /**
  1080. * Sets matrix on a uniform variable.
  1081. * @param uniformName Name of the variable.
  1082. * @param matrix matrix to be set.
  1083. * @returns this effect.
  1084. */
  1085. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1086. if (this._cacheMatrix(uniformName, matrix)) {
  1087. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1088. }
  1089. return this;
  1090. };
  1091. /**
  1092. * 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)
  1093. * @param uniformName Name of the variable.
  1094. * @param matrix matrix to be set.
  1095. * @returns this effect.
  1096. */
  1097. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1098. this._valueCache[uniformName] = null;
  1099. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1100. return this;
  1101. };
  1102. /**
  1103. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1104. * @param uniformName Name of the variable.
  1105. * @param matrix matrix to be set.
  1106. * @returns this effect.
  1107. */
  1108. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1109. this._valueCache[uniformName] = null;
  1110. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1111. return this;
  1112. };
  1113. /**
  1114. * Sets a float on a uniform variable.
  1115. * @param uniformName Name of the variable.
  1116. * @param value value to be set.
  1117. * @returns this effect.
  1118. */
  1119. Effect.prototype.setFloat = function (uniformName, value) {
  1120. var cache = this._valueCache[uniformName];
  1121. if (cache !== undefined && cache === value)
  1122. return this;
  1123. this._valueCache[uniformName] = value;
  1124. this._engine.setFloat(this.getUniform(uniformName), value);
  1125. return this;
  1126. };
  1127. /**
  1128. * Sets a boolean on a uniform variable.
  1129. * @param uniformName Name of the variable.
  1130. * @param bool value to be set.
  1131. * @returns this effect.
  1132. */
  1133. Effect.prototype.setBool = function (uniformName, bool) {
  1134. var cache = this._valueCache[uniformName];
  1135. if (cache !== undefined && cache === bool)
  1136. return this;
  1137. this._valueCache[uniformName] = bool;
  1138. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1139. return this;
  1140. };
  1141. /**
  1142. * Sets a Vector2 on a uniform variable.
  1143. * @param uniformName Name of the variable.
  1144. * @param vector2 vector2 to be set.
  1145. * @returns this effect.
  1146. */
  1147. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1148. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1149. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1150. }
  1151. return this;
  1152. };
  1153. /**
  1154. * Sets a float2 on a uniform variable.
  1155. * @param uniformName Name of the variable.
  1156. * @param x First float in float2.
  1157. * @param y Second float in float2.
  1158. * @returns this effect.
  1159. */
  1160. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1161. if (this._cacheFloat2(uniformName, x, y)) {
  1162. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1163. }
  1164. return this;
  1165. };
  1166. /**
  1167. * Sets a Vector3 on a uniform variable.
  1168. * @param uniformName Name of the variable.
  1169. * @param vector3 Value to be set.
  1170. * @returns this effect.
  1171. */
  1172. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1173. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1174. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1175. }
  1176. return this;
  1177. };
  1178. /**
  1179. * Sets a float3 on a uniform variable.
  1180. * @param uniformName Name of the variable.
  1181. * @param x First float in float3.
  1182. * @param y Second float in float3.
  1183. * @param z Third float in float3.
  1184. * @returns this effect.
  1185. */
  1186. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1187. if (this._cacheFloat3(uniformName, x, y, z)) {
  1188. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1189. }
  1190. return this;
  1191. };
  1192. /**
  1193. * Sets a Vector4 on a uniform variable.
  1194. * @param uniformName Name of the variable.
  1195. * @param vector4 Value to be set.
  1196. * @returns this effect.
  1197. */
  1198. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1199. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1200. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1201. }
  1202. return this;
  1203. };
  1204. /**
  1205. * Sets a float4 on a uniform variable.
  1206. * @param uniformName Name of the variable.
  1207. * @param x First float in float4.
  1208. * @param y Second float in float4.
  1209. * @param z Third float in float4.
  1210. * @param w Fourth float in float4.
  1211. * @returns this effect.
  1212. */
  1213. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1214. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1215. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1216. }
  1217. return this;
  1218. };
  1219. /**
  1220. * Sets a Color3 on a uniform variable.
  1221. * @param uniformName Name of the variable.
  1222. * @param color3 Value to be set.
  1223. * @returns this effect.
  1224. */
  1225. Effect.prototype.setColor3 = function (uniformName, color3) {
  1226. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1227. this._engine.setColor3(this.getUniform(uniformName), color3);
  1228. }
  1229. return this;
  1230. };
  1231. /**
  1232. * Sets a Color4 on a uniform variable.
  1233. * @param uniformName Name of the variable.
  1234. * @param color3 Value to be set.
  1235. * @param alpha Alpha value to be set.
  1236. * @returns this effect.
  1237. */
  1238. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1239. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1240. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1241. }
  1242. return this;
  1243. };
  1244. /**
  1245. * Sets a Color4 on a uniform variable
  1246. * @param uniformName defines the name of the variable
  1247. * @param color4 defines the value to be set
  1248. * @returns this effect.
  1249. */
  1250. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1251. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1252. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1253. }
  1254. return this;
  1255. };
  1256. /**
  1257. * Resets the cache of effects.
  1258. */
  1259. Effect.ResetCache = function () {
  1260. Effect._baseCache = {};
  1261. };
  1262. Effect._uniqueIdSeed = 0;
  1263. Effect._baseCache = {};
  1264. Effect._sourceCache = {};
  1265. // Statics
  1266. /**
  1267. * Store of each shader (The can be looked up using effect.key)
  1268. */
  1269. Effect.ShadersStore = {};
  1270. /**
  1271. * Store of each included file for a shader (The can be looked up using effect.key)
  1272. */
  1273. Effect.IncludesShadersStore = {};
  1274. return Effect;
  1275. }());
  1276. BABYLON.Effect = Effect;
  1277. })(BABYLON || (BABYLON = {}));
  1278. //# sourceMappingURL=babylon.effect.js.map
  1279. "use strict";
  1280. //# sourceMappingURL=babylon.types.js.map
  1281. "use strict";
  1282. var BABYLON;
  1283. (function (BABYLON) {
  1284. var KeyboardEventTypes = /** @class */ (function () {
  1285. function KeyboardEventTypes() {
  1286. }
  1287. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1288. get: function () {
  1289. return KeyboardEventTypes._KEYDOWN;
  1290. },
  1291. enumerable: true,
  1292. configurable: true
  1293. });
  1294. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1295. get: function () {
  1296. return KeyboardEventTypes._KEYUP;
  1297. },
  1298. enumerable: true,
  1299. configurable: true
  1300. });
  1301. KeyboardEventTypes._KEYDOWN = 0x01;
  1302. KeyboardEventTypes._KEYUP = 0x02;
  1303. return KeyboardEventTypes;
  1304. }());
  1305. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1306. var KeyboardInfo = /** @class */ (function () {
  1307. function KeyboardInfo(type, event) {
  1308. this.type = type;
  1309. this.event = event;
  1310. }
  1311. return KeyboardInfo;
  1312. }());
  1313. BABYLON.KeyboardInfo = KeyboardInfo;
  1314. /**
  1315. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1316. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1317. */
  1318. var KeyboardInfoPre = /** @class */ (function (_super) {
  1319. __extends(KeyboardInfoPre, _super);
  1320. function KeyboardInfoPre(type, event) {
  1321. var _this = _super.call(this, type, event) || this;
  1322. _this.skipOnPointerObservable = false;
  1323. return _this;
  1324. }
  1325. return KeyboardInfoPre;
  1326. }(KeyboardInfo));
  1327. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1328. })(BABYLON || (BABYLON = {}));
  1329. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1330. "use strict";
  1331. var BABYLON;
  1332. (function (BABYLON) {
  1333. var PointerEventTypes = /** @class */ (function () {
  1334. function PointerEventTypes() {
  1335. }
  1336. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1337. get: function () {
  1338. return PointerEventTypes._POINTERDOWN;
  1339. },
  1340. enumerable: true,
  1341. configurable: true
  1342. });
  1343. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1344. get: function () {
  1345. return PointerEventTypes._POINTERUP;
  1346. },
  1347. enumerable: true,
  1348. configurable: true
  1349. });
  1350. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1351. get: function () {
  1352. return PointerEventTypes._POINTERMOVE;
  1353. },
  1354. enumerable: true,
  1355. configurable: true
  1356. });
  1357. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1358. get: function () {
  1359. return PointerEventTypes._POINTERWHEEL;
  1360. },
  1361. enumerable: true,
  1362. configurable: true
  1363. });
  1364. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1365. get: function () {
  1366. return PointerEventTypes._POINTERPICK;
  1367. },
  1368. enumerable: true,
  1369. configurable: true
  1370. });
  1371. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1372. get: function () {
  1373. return PointerEventTypes._POINTERTAP;
  1374. },
  1375. enumerable: true,
  1376. configurable: true
  1377. });
  1378. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1379. get: function () {
  1380. return PointerEventTypes._POINTERDOUBLETAP;
  1381. },
  1382. enumerable: true,
  1383. configurable: true
  1384. });
  1385. PointerEventTypes._POINTERDOWN = 0x01;
  1386. PointerEventTypes._POINTERUP = 0x02;
  1387. PointerEventTypes._POINTERMOVE = 0x04;
  1388. PointerEventTypes._POINTERWHEEL = 0x08;
  1389. PointerEventTypes._POINTERPICK = 0x10;
  1390. PointerEventTypes._POINTERTAP = 0x20;
  1391. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1392. return PointerEventTypes;
  1393. }());
  1394. BABYLON.PointerEventTypes = PointerEventTypes;
  1395. var PointerInfoBase = /** @class */ (function () {
  1396. function PointerInfoBase(type, event) {
  1397. this.type = type;
  1398. this.event = event;
  1399. }
  1400. return PointerInfoBase;
  1401. }());
  1402. BABYLON.PointerInfoBase = PointerInfoBase;
  1403. /**
  1404. * This class is used to store pointer related info for the onPrePointerObservable event.
  1405. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1406. */
  1407. var PointerInfoPre = /** @class */ (function (_super) {
  1408. __extends(PointerInfoPre, _super);
  1409. function PointerInfoPre(type, event, localX, localY) {
  1410. var _this = _super.call(this, type, event) || this;
  1411. _this.skipOnPointerObservable = false;
  1412. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1413. return _this;
  1414. }
  1415. return PointerInfoPre;
  1416. }(PointerInfoBase));
  1417. BABYLON.PointerInfoPre = PointerInfoPre;
  1418. /**
  1419. * This type contains all the data related to a pointer event in Babylon.js.
  1420. * 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.
  1421. */
  1422. var PointerInfo = /** @class */ (function (_super) {
  1423. __extends(PointerInfo, _super);
  1424. function PointerInfo(type, event, pickInfo) {
  1425. var _this = _super.call(this, type, event) || this;
  1426. _this.pickInfo = pickInfo;
  1427. return _this;
  1428. }
  1429. return PointerInfo;
  1430. }(PointerInfoBase));
  1431. BABYLON.PointerInfo = PointerInfo;
  1432. })(BABYLON || (BABYLON = {}));
  1433. //# sourceMappingURL=babylon.pointerEvents.js.map
  1434. "use strict";
  1435. var BABYLON;
  1436. (function (BABYLON) {
  1437. BABYLON.ToGammaSpace = 1 / 2.2;
  1438. BABYLON.ToLinearSpace = 2.2;
  1439. BABYLON.Epsilon = 0.001;
  1440. /**
  1441. * Class used to hold a RBG color
  1442. */
  1443. var Color3 = /** @class */ (function () {
  1444. /**
  1445. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1446. * @param r defines the red component (between 0 and 1, default is 0)
  1447. * @param g defines the green component (between 0 and 1, default is 0)
  1448. * @param b defines the blue component (between 0 and 1, default is 0)
  1449. */
  1450. function Color3(
  1451. /**
  1452. * Defines the red component (between 0 and 1, default is 0)
  1453. */
  1454. r,
  1455. /**
  1456. * Defines the green component (between 0 and 1, default is 0)
  1457. */
  1458. g,
  1459. /**
  1460. * Defines the blue component (between 0 and 1, default is 0)
  1461. */
  1462. b) {
  1463. if (r === void 0) { r = 0; }
  1464. if (g === void 0) { g = 0; }
  1465. if (b === void 0) { b = 0; }
  1466. this.r = r;
  1467. this.g = g;
  1468. this.b = b;
  1469. }
  1470. /**
  1471. * Creates a string with the Color3 current values
  1472. * @returns the string representation of the Color3 object
  1473. */
  1474. Color3.prototype.toString = function () {
  1475. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1476. };
  1477. /**
  1478. * Returns the string "Color3"
  1479. * @returns "Color3"
  1480. */
  1481. Color3.prototype.getClassName = function () {
  1482. return "Color3";
  1483. };
  1484. /**
  1485. * Compute the Color3 hash code
  1486. * @returns an unique number that can be used to hash Color3 objects
  1487. */
  1488. Color3.prototype.getHashCode = function () {
  1489. var hash = this.r || 0;
  1490. hash = (hash * 397) ^ (this.g || 0);
  1491. hash = (hash * 397) ^ (this.b || 0);
  1492. return hash;
  1493. };
  1494. // Operators
  1495. /**
  1496. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements
  1497. * @param array defines the array where to store the r,g,b components
  1498. * @param index defines an optional index in the target array to define where to start storing values
  1499. * @returns the current Color3 object
  1500. */
  1501. Color3.prototype.toArray = function (array, index) {
  1502. if (index === undefined) {
  1503. index = 0;
  1504. }
  1505. array[index] = this.r;
  1506. array[index + 1] = this.g;
  1507. array[index + 2] = this.b;
  1508. return this;
  1509. };
  1510. /**
  1511. * Returns a new {BABYLON.Color4} object from the current Color3 and the passed alpha
  1512. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1513. * @returns a new {BABYLON.Color4} object
  1514. */
  1515. Color3.prototype.toColor4 = function (alpha) {
  1516. if (alpha === void 0) { alpha = 1; }
  1517. return new Color4(this.r, this.g, this.b, alpha);
  1518. };
  1519. /**
  1520. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1521. * @returns the new array
  1522. */
  1523. Color3.prototype.asArray = function () {
  1524. var result = new Array();
  1525. this.toArray(result, 0);
  1526. return result;
  1527. };
  1528. /**
  1529. * Returns the luminance value
  1530. * @returns a float value
  1531. */
  1532. Color3.prototype.toLuminance = function () {
  1533. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1534. };
  1535. /**
  1536. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object
  1537. * @param otherColor defines the second operand
  1538. * @returns the new Color3 object
  1539. */
  1540. Color3.prototype.multiply = function (otherColor) {
  1541. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1542. };
  1543. /**
  1544. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result"
  1545. * @param otherColor defines the second operand
  1546. * @param result defines the Color3 object where to store the result
  1547. * @returns the current Color3
  1548. */
  1549. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1550. result.r = this.r * otherColor.r;
  1551. result.g = this.g * otherColor.g;
  1552. result.b = this.b * otherColor.b;
  1553. return this;
  1554. };
  1555. /**
  1556. * Determines equality between Color3 objects
  1557. * @param otherColor defines the second operand
  1558. * @returns true if the rgb values are equal to the passed ones
  1559. */
  1560. Color3.prototype.equals = function (otherColor) {
  1561. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1562. };
  1563. /**
  1564. * Determines equality between the current Color3 object and a set of r,b,g values
  1565. * @param r defines the red component to check
  1566. * @param g defines the green component to check
  1567. * @param b defines the blue component to check
  1568. * @returns true if the rgb values are equal to the passed ones
  1569. */
  1570. Color3.prototype.equalsFloats = function (r, g, b) {
  1571. return this.r === r && this.g === g && this.b === b;
  1572. };
  1573. /**
  1574. * Multiplies in place each rgb value by scale
  1575. * @param scale defines the scaling factor
  1576. * @returns the updated Color3
  1577. */
  1578. Color3.prototype.scale = function (scale) {
  1579. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1580. };
  1581. /**
  1582. * Multiplies the rgb values by scale and stores the result into "result"
  1583. * @param scale defines the scaling factor
  1584. * @param result defines the Color3 object where to store the result
  1585. * @returns the unmodified current Color3
  1586. */
  1587. Color3.prototype.scaleToRef = function (scale, result) {
  1588. result.r = this.r * scale;
  1589. result.g = this.g * scale;
  1590. result.b = this.b * scale;
  1591. return this;
  1592. };
  1593. /**
  1594. * Scale the current Color3 values by a factor and add the result to a given Color3
  1595. * @param scale defines the scale factor
  1596. * @param result defines color to store the result into
  1597. * @returns the unmodified current Color3
  1598. */
  1599. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1600. result.r += this.r * scale;
  1601. result.g += this.g * scale;
  1602. result.b += this.b * scale;
  1603. return this;
  1604. };
  1605. /**
  1606. * Clamps the rgb values by the min and max values and stores the result into "result"
  1607. * @param min defines minimum clamping value (default is 0)
  1608. * @param max defines maximum clamping value (default is 1)
  1609. * @param result defines color to store the result into
  1610. * @returns the original Color3
  1611. */
  1612. Color3.prototype.clampToRef = function (min, max, result) {
  1613. if (min === void 0) { min = 0; }
  1614. if (max === void 0) { max = 1; }
  1615. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1616. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1617. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1618. return this;
  1619. };
  1620. /**
  1621. * Creates a new Color3 set with the added values of the current Color3 and of the passed one
  1622. * @param otherColor defines the second operand
  1623. * @returns the new Color3
  1624. */
  1625. Color3.prototype.add = function (otherColor) {
  1626. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1627. };
  1628. /**
  1629. * Stores the result of the addition of the current Color3 and passed one rgb values into "result"
  1630. * @param otherColor defines the second operand
  1631. * @param result defines Color3 object to store the result into
  1632. * @returns the unmodified current Color3
  1633. */
  1634. Color3.prototype.addToRef = function (otherColor, result) {
  1635. result.r = this.r + otherColor.r;
  1636. result.g = this.g + otherColor.g;
  1637. result.b = this.b + otherColor.b;
  1638. return this;
  1639. };
  1640. /**
  1641. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3
  1642. * @param otherColor defines the second operand
  1643. * @returns the new Color3
  1644. */
  1645. Color3.prototype.subtract = function (otherColor) {
  1646. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1647. };
  1648. /**
  1649. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result"
  1650. * @param otherColor defines the second operand
  1651. * @param result defines Color3 object to store the result into
  1652. * @returns the unmodified current Color3
  1653. */
  1654. Color3.prototype.subtractToRef = function (otherColor, result) {
  1655. result.r = this.r - otherColor.r;
  1656. result.g = this.g - otherColor.g;
  1657. result.b = this.b - otherColor.b;
  1658. return this;
  1659. };
  1660. /**
  1661. * Copy the current object
  1662. * @returns a new Color3 copied the current one
  1663. */
  1664. Color3.prototype.clone = function () {
  1665. return new Color3(this.r, this.g, this.b);
  1666. };
  1667. /**
  1668. * Copies the rgb values from the source in the current Color3
  1669. * @param source defines the source Color3 object
  1670. * @returns the updated Color3 object
  1671. */
  1672. Color3.prototype.copyFrom = function (source) {
  1673. this.r = source.r;
  1674. this.g = source.g;
  1675. this.b = source.b;
  1676. return this;
  1677. };
  1678. /**
  1679. * Updates the Color3 rgb values from the passed floats
  1680. * @param r defines the red component to read from
  1681. * @param g defines the green component to read from
  1682. * @param b defines the blue component to read from
  1683. * @returns the current Color3 object
  1684. */
  1685. Color3.prototype.copyFromFloats = function (r, g, b) {
  1686. this.r = r;
  1687. this.g = g;
  1688. this.b = b;
  1689. return this;
  1690. };
  1691. /**
  1692. * Updates the Color3 rgb values from the passed floats
  1693. * @param r defines the red component to read from
  1694. * @param g defines the green component to read from
  1695. * @param b defines the blue component to read from
  1696. * @returns the current Color3 object
  1697. */
  1698. Color3.prototype.set = function (r, g, b) {
  1699. return this.copyFromFloats(r, g, b);
  1700. };
  1701. /**
  1702. * Compute the Color3 hexadecimal code as a string
  1703. * @returns a string containing the hexadecimal representation of the Color3 object
  1704. */
  1705. Color3.prototype.toHexString = function () {
  1706. var intR = (this.r * 255) | 0;
  1707. var intG = (this.g * 255) | 0;
  1708. var intB = (this.b * 255) | 0;
  1709. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1710. };
  1711. /**
  1712. * Computes a new Color3 converted from the current one to linear space
  1713. * @returns a new Color3 object
  1714. */
  1715. Color3.prototype.toLinearSpace = function () {
  1716. var convertedColor = new Color3();
  1717. this.toLinearSpaceToRef(convertedColor);
  1718. return convertedColor;
  1719. };
  1720. /**
  1721. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1722. * @param convertedColor defines the Color3 object where to store the linear space version
  1723. * @returns the unmodified Color3
  1724. */
  1725. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1726. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1727. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1728. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1729. return this;
  1730. };
  1731. /**
  1732. * Computes a new Color3 converted from the current one to gamma space
  1733. * @returns a new Color3 object
  1734. */
  1735. Color3.prototype.toGammaSpace = function () {
  1736. var convertedColor = new Color3();
  1737. this.toGammaSpaceToRef(convertedColor);
  1738. return convertedColor;
  1739. };
  1740. /**
  1741. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1742. * @param convertedColor defines the Color3 object where to store the gamma space version
  1743. * @returns the unmodified Color3
  1744. */
  1745. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1746. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1747. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1748. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1749. return this;
  1750. };
  1751. // Statics
  1752. /**
  1753. * Creates a new Color3 from the string containing valid hexadecimal values
  1754. * @param hex defines a string containing valid hexadecimal values
  1755. * @returns a new Color3 object
  1756. */
  1757. Color3.FromHexString = function (hex) {
  1758. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1759. return new Color3(0, 0, 0);
  1760. }
  1761. var r = parseInt(hex.substring(1, 3), 16);
  1762. var g = parseInt(hex.substring(3, 5), 16);
  1763. var b = parseInt(hex.substring(5, 7), 16);
  1764. return Color3.FromInts(r, g, b);
  1765. };
  1766. /**
  1767. * Creates a new Vector3 from the starting index of the passed array
  1768. * @param array defines the source array
  1769. * @param offset defines an offset in the source array
  1770. * @returns a new Color3 object
  1771. */
  1772. Color3.FromArray = function (array, offset) {
  1773. if (offset === void 0) { offset = 0; }
  1774. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1775. };
  1776. /**
  1777. * Creates a new Color3 from integer values (< 256)
  1778. * @param r defines the red component to read from (value between 0 and 255)
  1779. * @param g defines the green component to read from (value between 0 and 255)
  1780. * @param b defines the blue component to read from (value between 0 and 255)
  1781. * @returns a new Color3 object
  1782. */
  1783. Color3.FromInts = function (r, g, b) {
  1784. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1785. };
  1786. /**
  1787. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1788. * @param start defines the start Color3 value
  1789. * @param end defines the end Color3 value
  1790. * @param amount defines the gradient value between start and end
  1791. * @returns a new Color3 object
  1792. */
  1793. Color3.Lerp = function (start, end, amount) {
  1794. var r = start.r + ((end.r - start.r) * amount);
  1795. var g = start.g + ((end.g - start.g) * amount);
  1796. var b = start.b + ((end.b - start.b) * amount);
  1797. return new Color3(r, g, b);
  1798. };
  1799. /**
  1800. * Returns a Color3 value containing a red color
  1801. * @returns a new Color3 object
  1802. */
  1803. Color3.Red = function () { return new Color3(1, 0, 0); };
  1804. /**
  1805. * Returns a Color3 value containing a green color
  1806. * @returns a new Color3 object
  1807. */
  1808. Color3.Green = function () { return new Color3(0, 1, 0); };
  1809. /**
  1810. * Returns a Color3 value containing a blue color
  1811. * @returns a new Color3 object
  1812. */
  1813. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1814. /**
  1815. * Returns a Color3 value containing a black color
  1816. * @returns a new Color3 object
  1817. */
  1818. Color3.Black = function () { return new Color3(0, 0, 0); };
  1819. /**
  1820. * Returns a Color3 value containing a white color
  1821. * @returns a new Color3 object
  1822. */
  1823. Color3.White = function () { return new Color3(1, 1, 1); };
  1824. /**
  1825. * Returns a Color3 value containing a purple color
  1826. * @returns a new Color3 object
  1827. */
  1828. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1829. /**
  1830. * Returns a Color3 value containing a magenta color
  1831. * @returns a new Color3 object
  1832. */
  1833. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1834. /**
  1835. * Returns a Color3 value containing a yellow color
  1836. * @returns a new Color3 object
  1837. */
  1838. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1839. /**
  1840. * Returns a Color3 value containing a gray color
  1841. * @returns a new Color3 object
  1842. */
  1843. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1844. /**
  1845. * Returns a Color3 value containing a teal color
  1846. * @returns a new Color3 object
  1847. */
  1848. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1849. /**
  1850. * Returns a Color3 value containing a random color
  1851. * @returns a new Color3 object
  1852. */
  1853. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1854. return Color3;
  1855. }());
  1856. BABYLON.Color3 = Color3;
  1857. /**
  1858. * Class used to hold a RBGA color
  1859. */
  1860. var Color4 = /** @class */ (function () {
  1861. /**
  1862. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1863. * @param r defines the red component (between 0 and 1, default is 0)
  1864. * @param g defines the green component (between 0 and 1, default is 0)
  1865. * @param b defines the blue component (between 0 and 1, default is 0)
  1866. * @param a defines the alpha component (between 0 and 1, default is 1)
  1867. */
  1868. function Color4(
  1869. /**
  1870. * Defines the red component (between 0 and 1, default is 0)
  1871. */
  1872. r,
  1873. /**
  1874. * Defines the green component (between 0 and 1, default is 0)
  1875. */
  1876. g,
  1877. /**
  1878. * Defines the blue component (between 0 and 1, default is 0)
  1879. */
  1880. b,
  1881. /**
  1882. * Defines the alpha component (between 0 and 1, default is 1)
  1883. */
  1884. a) {
  1885. if (r === void 0) { r = 0; }
  1886. if (g === void 0) { g = 0; }
  1887. if (b === void 0) { b = 0; }
  1888. if (a === void 0) { a = 1; }
  1889. this.r = r;
  1890. this.g = g;
  1891. this.b = b;
  1892. this.a = a;
  1893. }
  1894. // Operators
  1895. /**
  1896. * Adds in place the passed Color4 values to the current Color4 object
  1897. * @param right defines the second operand
  1898. * @returns the current updated Color4 object
  1899. */
  1900. Color4.prototype.addInPlace = function (right) {
  1901. this.r += right.r;
  1902. this.g += right.g;
  1903. this.b += right.b;
  1904. this.a += right.a;
  1905. return this;
  1906. };
  1907. /**
  1908. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1909. * @returns the new array
  1910. */
  1911. Color4.prototype.asArray = function () {
  1912. var result = new Array();
  1913. this.toArray(result, 0);
  1914. return result;
  1915. };
  1916. /**
  1917. * Stores from the starting index in the passed array the Color4 successive values
  1918. * @param array defines the array where to store the r,g,b components
  1919. * @param index defines an optional index in the target array to define where to start storing values
  1920. * @returns the current Color4 object
  1921. */
  1922. Color4.prototype.toArray = function (array, index) {
  1923. if (index === undefined) {
  1924. index = 0;
  1925. }
  1926. array[index] = this.r;
  1927. array[index + 1] = this.g;
  1928. array[index + 2] = this.b;
  1929. array[index + 3] = this.a;
  1930. return this;
  1931. };
  1932. /**
  1933. * Creates a new Color4 set with the added values of the current Color4 and of the passed one
  1934. * @param right defines the second operand
  1935. * @returns a new Color4 object
  1936. */
  1937. Color4.prototype.add = function (right) {
  1938. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1939. };
  1940. /**
  1941. * Creates a new Color4 set with the subtracted values of the passed one from the current Color4
  1942. * @param right defines the second operand
  1943. * @returns a new Color4 object
  1944. */
  1945. Color4.prototype.subtract = function (right) {
  1946. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1947. };
  1948. /**
  1949. * Subtracts the passed ones from the current Color4 values and stores the results in "result"
  1950. * @param right defines the second operand
  1951. * @param result defines the Color4 object where to store the result
  1952. * @returns the current Color4 object
  1953. */
  1954. Color4.prototype.subtractToRef = function (right, result) {
  1955. result.r = this.r - right.r;
  1956. result.g = this.g - right.g;
  1957. result.b = this.b - right.b;
  1958. result.a = this.a - right.a;
  1959. return this;
  1960. };
  1961. /**
  1962. * Creates a new Color4 with the current Color4 values multiplied by scale
  1963. * @param scale defines the scaling factor to apply
  1964. * @returns a new Color4 object
  1965. */
  1966. Color4.prototype.scale = function (scale) {
  1967. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1968. };
  1969. /**
  1970. * Multiplies the current Color4 values by scale and stores the result in "result"
  1971. * @param scale defines the scaling factor to apply
  1972. * @param result defines the Color4 object where to store the result
  1973. * @returns the current unmodified Color4
  1974. */
  1975. Color4.prototype.scaleToRef = function (scale, result) {
  1976. result.r = this.r * scale;
  1977. result.g = this.g * scale;
  1978. result.b = this.b * scale;
  1979. result.a = this.a * scale;
  1980. return this;
  1981. };
  1982. /**
  1983. * Scale the current Color4 values by a factor and add the result to a given Color4
  1984. * @param scale defines the scale factor
  1985. * @param result defines the Color4 object where to store the result
  1986. * @returns the unmodified current Color4
  1987. */
  1988. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1989. result.r += this.r * scale;
  1990. result.g += this.g * scale;
  1991. result.b += this.b * scale;
  1992. result.a += this.a * scale;
  1993. return this;
  1994. };
  1995. /**
  1996. * Clamps the rgb values by the min and max values and stores the result into "result"
  1997. * @param min defines minimum clamping value (default is 0)
  1998. * @param max defines maximum clamping value (default is 1)
  1999. * @param result defines color to store the result into.
  2000. * @returns the cuurent Color4
  2001. */
  2002. Color4.prototype.clampToRef = function (min, max, result) {
  2003. if (min === void 0) { min = 0; }
  2004. if (max === void 0) { max = 1; }
  2005. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  2006. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  2007. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  2008. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  2009. return this;
  2010. };
  2011. /**
  2012. * Multipy an Color4 value by another and return a new Color4 object
  2013. * @param color defines the Color4 value to multiply by
  2014. * @returns a new Color4 object
  2015. */
  2016. Color4.prototype.multiply = function (color) {
  2017. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  2018. };
  2019. /**
  2020. * Multipy a Color4 value by another and push the result in a reference value
  2021. * @param color defines the Color4 value to multiply by
  2022. * @param result defines the Color4 to fill the result in
  2023. * @returns the result Color4
  2024. */
  2025. Color4.prototype.multiplyToRef = function (color, result) {
  2026. result.r = this.r * color.r;
  2027. result.g = this.g * color.g;
  2028. result.b = this.b * color.b;
  2029. result.a = this.a * color.a;
  2030. return result;
  2031. };
  2032. /**
  2033. * Creates a string with the Color4 current values
  2034. * @returns the string representation of the Color4 object
  2035. */
  2036. Color4.prototype.toString = function () {
  2037. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2038. };
  2039. /**
  2040. * Returns the string "Color4"
  2041. * @returns "Color4"
  2042. */
  2043. Color4.prototype.getClassName = function () {
  2044. return "Color4";
  2045. };
  2046. /**
  2047. * Compute the Color4 hash code
  2048. * @returns an unique number that can be used to hash Color4 objects
  2049. */
  2050. Color4.prototype.getHashCode = function () {
  2051. var hash = this.r || 0;
  2052. hash = (hash * 397) ^ (this.g || 0);
  2053. hash = (hash * 397) ^ (this.b || 0);
  2054. hash = (hash * 397) ^ (this.a || 0);
  2055. return hash;
  2056. };
  2057. /**
  2058. * Creates a new Color4 copied from the current one
  2059. * @returns a new Color4 object
  2060. */
  2061. Color4.prototype.clone = function () {
  2062. return new Color4(this.r, this.g, this.b, this.a);
  2063. };
  2064. /**
  2065. * Copies the passed Color4 values into the current one
  2066. * @param source defines the source Color4 object
  2067. * @returns the current updated Color4 object
  2068. */
  2069. Color4.prototype.copyFrom = function (source) {
  2070. this.r = source.r;
  2071. this.g = source.g;
  2072. this.b = source.b;
  2073. this.a = source.a;
  2074. return this;
  2075. };
  2076. /**
  2077. * Copies the passed float values into the current one
  2078. * @param r defines the red component to read from
  2079. * @param g defines the green component to read from
  2080. * @param b defines the blue component to read from
  2081. * @param a defines the alpha component to read from
  2082. * @returns the current updated Color4 object
  2083. */
  2084. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2085. this.r = r;
  2086. this.g = g;
  2087. this.b = b;
  2088. this.a = a;
  2089. return this;
  2090. };
  2091. /**
  2092. * Copies the passed float values into the current one
  2093. * @param r defines the red component to read from
  2094. * @param g defines the green component to read from
  2095. * @param b defines the blue component to read from
  2096. * @param a defines the alpha component to read from
  2097. * @returns the current updated Color4 object
  2098. */
  2099. Color4.prototype.set = function (r, g, b, a) {
  2100. return this.copyFromFloats(r, g, b, a);
  2101. };
  2102. /**
  2103. * Compute the Color4 hexadecimal code as a string
  2104. * @returns a string containing the hexadecimal representation of the Color4 object
  2105. */
  2106. Color4.prototype.toHexString = function () {
  2107. var intR = (this.r * 255) | 0;
  2108. var intG = (this.g * 255) | 0;
  2109. var intB = (this.b * 255) | 0;
  2110. var intA = (this.a * 255) | 0;
  2111. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2112. };
  2113. /**
  2114. * Computes a new Color4 converted from the current one to linear space
  2115. * @returns a new Color4 object
  2116. */
  2117. Color4.prototype.toLinearSpace = function () {
  2118. var convertedColor = new Color4();
  2119. this.toLinearSpaceToRef(convertedColor);
  2120. return convertedColor;
  2121. };
  2122. /**
  2123. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2124. * @param convertedColor defines the Color4 object where to store the linear space version
  2125. * @returns the unmodified Color4
  2126. */
  2127. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2128. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2129. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2130. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2131. convertedColor.a = this.a;
  2132. return this;
  2133. };
  2134. /**
  2135. * Computes a new Color4 converted from the current one to gamma space
  2136. * @returns a new Color4 object
  2137. */
  2138. Color4.prototype.toGammaSpace = function () {
  2139. var convertedColor = new Color4();
  2140. this.toGammaSpaceToRef(convertedColor);
  2141. return convertedColor;
  2142. };
  2143. /**
  2144. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2145. * @param convertedColor defines the Color4 object where to store the gamma space version
  2146. * @returns the unmodified Color4
  2147. */
  2148. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2149. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2150. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2151. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2152. convertedColor.a = this.a;
  2153. return this;
  2154. };
  2155. // Statics
  2156. /**
  2157. * Creates a new Color4 from the string containing valid hexadecimal values
  2158. * @param hex defines a string containing valid hexadecimal values
  2159. * @returns a new Color4 object
  2160. */
  2161. Color4.FromHexString = function (hex) {
  2162. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2163. return new Color4(0.0, 0.0, 0.0, 0.0);
  2164. }
  2165. var r = parseInt(hex.substring(1, 3), 16);
  2166. var g = parseInt(hex.substring(3, 5), 16);
  2167. var b = parseInt(hex.substring(5, 7), 16);
  2168. var a = parseInt(hex.substring(7, 9), 16);
  2169. return Color4.FromInts(r, g, b, a);
  2170. };
  2171. /**
  2172. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2173. * @param left defines the start value
  2174. * @param right defines the end value
  2175. * @param amount defines the gradient factor
  2176. * @returns a new Color4 object
  2177. */
  2178. Color4.Lerp = function (left, right, amount) {
  2179. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2180. Color4.LerpToRef(left, right, amount, result);
  2181. return result;
  2182. };
  2183. /**
  2184. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2185. * @param left defines the start value
  2186. * @param right defines the end value
  2187. * @param amount defines the gradient factor
  2188. * @param result defines the Color4 object where to store data
  2189. */
  2190. Color4.LerpToRef = function (left, right, amount, result) {
  2191. result.r = left.r + (right.r - left.r) * amount;
  2192. result.g = left.g + (right.g - left.g) * amount;
  2193. result.b = left.b + (right.b - left.b) * amount;
  2194. result.a = left.a + (right.a - left.a) * amount;
  2195. };
  2196. /**
  2197. * Creates a new Color4 from the starting index element of the passed array
  2198. * @param array defines the source array to read from
  2199. * @param offset defines the offset in the source array
  2200. * @returns a new Color4 object
  2201. */
  2202. Color4.FromArray = function (array, offset) {
  2203. if (offset === void 0) { offset = 0; }
  2204. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2205. };
  2206. /**
  2207. * Creates a new Color3 from integer values (< 256)
  2208. * @param r defines the red component to read from (value between 0 and 255)
  2209. * @param g defines the green component to read from (value between 0 and 255)
  2210. * @param b defines the blue component to read from (value between 0 and 255)
  2211. * @param a defines the alpha component to read from (value between 0 and 255)
  2212. * @returns a new Color3 object
  2213. */
  2214. Color4.FromInts = function (r, g, b, a) {
  2215. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2216. };
  2217. /**
  2218. * Check the content of a given array and convert it to an array containing RGBA data
  2219. * If the original array was already containing count * 4 values then it is returned directly
  2220. * @param colors defines the array to check
  2221. * @param count defines the number of RGBA data to expect
  2222. * @returns an array containing count * 4 values (RGBA)
  2223. */
  2224. Color4.CheckColors4 = function (colors, count) {
  2225. // Check if color3 was used
  2226. if (colors.length === count * 3) {
  2227. var colors4 = [];
  2228. for (var index = 0; index < colors.length; index += 3) {
  2229. var newIndex = (index / 3) * 4;
  2230. colors4[newIndex] = colors[index];
  2231. colors4[newIndex + 1] = colors[index + 1];
  2232. colors4[newIndex + 2] = colors[index + 2];
  2233. colors4[newIndex + 3] = 1.0;
  2234. }
  2235. return colors4;
  2236. }
  2237. return colors;
  2238. };
  2239. return Color4;
  2240. }());
  2241. BABYLON.Color4 = Color4;
  2242. var Vector2 = /** @class */ (function () {
  2243. /**
  2244. * Creates a new Vector2 from the passed x and y coordinates.
  2245. */
  2246. function Vector2(x, y) {
  2247. this.x = x;
  2248. this.y = y;
  2249. }
  2250. /**
  2251. * Returns a string with the Vector2 coordinates.
  2252. */
  2253. Vector2.prototype.toString = function () {
  2254. return "{X: " + this.x + " Y:" + this.y + "}";
  2255. };
  2256. /**
  2257. * Returns the string "Vector2"
  2258. */
  2259. Vector2.prototype.getClassName = function () {
  2260. return "Vector2";
  2261. };
  2262. /**
  2263. * Returns the Vector2 hash code as a number.
  2264. */
  2265. Vector2.prototype.getHashCode = function () {
  2266. var hash = this.x || 0;
  2267. hash = (hash * 397) ^ (this.y || 0);
  2268. return hash;
  2269. };
  2270. // Operators
  2271. /**
  2272. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  2273. * Returns the Vector2.
  2274. */
  2275. Vector2.prototype.toArray = function (array, index) {
  2276. if (index === void 0) { index = 0; }
  2277. array[index] = this.x;
  2278. array[index + 1] = this.y;
  2279. return this;
  2280. };
  2281. /**
  2282. * Returns a new array with 2 elements : the Vector2 coordinates.
  2283. */
  2284. Vector2.prototype.asArray = function () {
  2285. var result = new Array();
  2286. this.toArray(result, 0);
  2287. return result;
  2288. };
  2289. /**
  2290. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  2291. * Returns the updated Vector2.
  2292. */
  2293. Vector2.prototype.copyFrom = function (source) {
  2294. this.x = source.x;
  2295. this.y = source.y;
  2296. return this;
  2297. };
  2298. /**
  2299. * Sets the Vector2 coordinates with the passed floats.
  2300. * Returns the updated Vector2.
  2301. */
  2302. Vector2.prototype.copyFromFloats = function (x, y) {
  2303. this.x = x;
  2304. this.y = y;
  2305. return this;
  2306. };
  2307. /**
  2308. * Sets the Vector2 coordinates with the passed floats.
  2309. * Returns the updated Vector2.
  2310. */
  2311. Vector2.prototype.set = function (x, y) {
  2312. return this.copyFromFloats(x, y);
  2313. };
  2314. /**
  2315. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  2316. */
  2317. Vector2.prototype.add = function (otherVector) {
  2318. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2319. };
  2320. /**
  2321. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  2322. * Returns the Vector2.
  2323. */
  2324. Vector2.prototype.addToRef = function (otherVector, result) {
  2325. result.x = this.x + otherVector.x;
  2326. result.y = this.y + otherVector.y;
  2327. return this;
  2328. };
  2329. /**
  2330. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  2331. * Returns the updated Vector2.
  2332. */
  2333. Vector2.prototype.addInPlace = function (otherVector) {
  2334. this.x += otherVector.x;
  2335. this.y += otherVector.y;
  2336. return this;
  2337. };
  2338. /**
  2339. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  2340. */
  2341. Vector2.prototype.addVector3 = function (otherVector) {
  2342. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2343. };
  2344. /**
  2345. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  2346. */
  2347. Vector2.prototype.subtract = function (otherVector) {
  2348. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2349. };
  2350. /**
  2351. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  2352. * Returns the Vector2.
  2353. */
  2354. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2355. result.x = this.x - otherVector.x;
  2356. result.y = this.y - otherVector.y;
  2357. return this;
  2358. };
  2359. /**
  2360. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  2361. * Returns the updated Vector2.
  2362. */
  2363. Vector2.prototype.subtractInPlace = function (otherVector) {
  2364. this.x -= otherVector.x;
  2365. this.y -= otherVector.y;
  2366. return this;
  2367. };
  2368. /**
  2369. * Multiplies in place the current Vector2 coordinates by the passed ones.
  2370. * Returns the updated Vector2.
  2371. */
  2372. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2373. this.x *= otherVector.x;
  2374. this.y *= otherVector.y;
  2375. return this;
  2376. };
  2377. /**
  2378. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  2379. */
  2380. Vector2.prototype.multiply = function (otherVector) {
  2381. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2382. };
  2383. /**
  2384. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  2385. * Returns the Vector2.
  2386. */
  2387. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2388. result.x = this.x * otherVector.x;
  2389. result.y = this.y * otherVector.y;
  2390. return this;
  2391. };
  2392. /**
  2393. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  2394. */
  2395. Vector2.prototype.multiplyByFloats = function (x, y) {
  2396. return new Vector2(this.x * x, this.y * y);
  2397. };
  2398. /**
  2399. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  2400. */
  2401. Vector2.prototype.divide = function (otherVector) {
  2402. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2403. };
  2404. /**
  2405. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  2406. * Returns the Vector2.
  2407. */
  2408. Vector2.prototype.divideToRef = function (otherVector, result) {
  2409. result.x = this.x / otherVector.x;
  2410. result.y = this.y / otherVector.y;
  2411. return this;
  2412. };
  2413. /**
  2414. * Divides the current Vector3 coordinates by the passed ones.
  2415. * Returns the updated Vector3.
  2416. */
  2417. Vector2.prototype.divideInPlace = function (otherVector) {
  2418. return this.divideToRef(otherVector, this);
  2419. };
  2420. /**
  2421. * Returns a new Vector2 with current Vector2 negated coordinates.
  2422. */
  2423. Vector2.prototype.negate = function () {
  2424. return new Vector2(-this.x, -this.y);
  2425. };
  2426. /**
  2427. * Multiply the Vector2 coordinates by scale.
  2428. * Returns the 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. */
  2438. Vector2.prototype.scale = function (scale) {
  2439. var result = new Vector2(0, 0);
  2440. this.scaleToRef(scale, result);
  2441. return result;
  2442. };
  2443. /**
  2444. * Scale the current Vector2 values by a factor to a given Vector2
  2445. * @param scale defines the scale factor
  2446. * @param result defines the Vector2 object where to store the result
  2447. * @returns the unmodified current Vector2
  2448. */
  2449. Vector2.prototype.scaleToRef = function (scale, result) {
  2450. result.x = this.x * scale;
  2451. result.y = this.y * scale;
  2452. return this;
  2453. };
  2454. /**
  2455. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2456. * @param scale defines the scale factor
  2457. * @param result defines the Vector2 object where to store the result
  2458. * @returns the unmodified current Vector2
  2459. */
  2460. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2461. result.x += this.x * scale;
  2462. result.y += this.y * scale;
  2463. return this;
  2464. };
  2465. /**
  2466. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  2467. */
  2468. Vector2.prototype.equals = function (otherVector) {
  2469. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2470. };
  2471. /**
  2472. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  2473. */
  2474. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2475. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2476. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2477. };
  2478. // Properties
  2479. /**
  2480. * Returns the vector length (float).
  2481. */
  2482. Vector2.prototype.length = function () {
  2483. return Math.sqrt(this.x * this.x + this.y * this.y);
  2484. };
  2485. /**
  2486. * Returns the vector squared length (float);
  2487. */
  2488. Vector2.prototype.lengthSquared = function () {
  2489. return (this.x * this.x + this.y * this.y);
  2490. };
  2491. // Methods
  2492. /**
  2493. * Normalize the vector.
  2494. * Returns the updated Vector2.
  2495. */
  2496. Vector2.prototype.normalize = function () {
  2497. var len = this.length();
  2498. if (len === 0)
  2499. return this;
  2500. var num = 1.0 / len;
  2501. this.x *= num;
  2502. this.y *= num;
  2503. return this;
  2504. };
  2505. /**
  2506. * Returns a new Vector2 copied from the Vector2.
  2507. */
  2508. Vector2.prototype.clone = function () {
  2509. return new Vector2(this.x, this.y);
  2510. };
  2511. // Statics
  2512. /**
  2513. * Returns a new Vector2(0, 0)
  2514. */
  2515. Vector2.Zero = function () {
  2516. return new Vector2(0, 0);
  2517. };
  2518. /**
  2519. * Returns a new Vector2(1, 1)
  2520. */
  2521. Vector2.One = function () {
  2522. return new Vector2(1, 1);
  2523. };
  2524. /**
  2525. * Returns a new Vector2 set from the passed index element of the passed array.
  2526. */
  2527. Vector2.FromArray = function (array, offset) {
  2528. if (offset === void 0) { offset = 0; }
  2529. return new Vector2(array[offset], array[offset + 1]);
  2530. };
  2531. /**
  2532. * Sets "result" from the passed index element of the passed array.
  2533. */
  2534. Vector2.FromArrayToRef = function (array, offset, result) {
  2535. result.x = array[offset];
  2536. result.y = array[offset + 1];
  2537. };
  2538. /**
  2539. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  2540. */
  2541. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2542. var squared = amount * amount;
  2543. var cubed = amount * squared;
  2544. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2545. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2546. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2547. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2548. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2549. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2550. return new Vector2(x, y);
  2551. };
  2552. /**
  2553. * 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".
  2554. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2555. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  2556. */
  2557. Vector2.Clamp = function (value, min, max) {
  2558. var x = value.x;
  2559. x = (x > max.x) ? max.x : x;
  2560. x = (x < min.x) ? min.x : x;
  2561. var y = value.y;
  2562. y = (y > max.y) ? max.y : y;
  2563. y = (y < min.y) ? min.y : y;
  2564. return new Vector2(x, y);
  2565. };
  2566. /**
  2567. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  2568. */
  2569. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2570. var squared = amount * amount;
  2571. var cubed = amount * squared;
  2572. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2573. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2574. var part3 = (cubed - (2.0 * squared)) + amount;
  2575. var part4 = cubed - squared;
  2576. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2577. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2578. return new Vector2(x, y);
  2579. };
  2580. /**
  2581. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2582. */
  2583. Vector2.Lerp = function (start, end, amount) {
  2584. var x = start.x + ((end.x - start.x) * amount);
  2585. var y = start.y + ((end.y - start.y) * amount);
  2586. return new Vector2(x, y);
  2587. };
  2588. /**
  2589. * Returns the dot product (float) of the vector "left" and the vector "right".
  2590. */
  2591. Vector2.Dot = function (left, right) {
  2592. return left.x * right.x + left.y * right.y;
  2593. };
  2594. /**
  2595. * Returns a new Vector2 equal to the normalized passed vector.
  2596. */
  2597. Vector2.Normalize = function (vector) {
  2598. var newVector = vector.clone();
  2599. newVector.normalize();
  2600. return newVector;
  2601. };
  2602. /**
  2603. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  2604. */
  2605. Vector2.Minimize = function (left, right) {
  2606. var x = (left.x < right.x) ? left.x : right.x;
  2607. var y = (left.y < right.y) ? left.y : right.y;
  2608. return new Vector2(x, y);
  2609. };
  2610. /**
  2611. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  2612. */
  2613. Vector2.Maximize = function (left, right) {
  2614. var x = (left.x > right.x) ? left.x : right.x;
  2615. var y = (left.y > right.y) ? left.y : right.y;
  2616. return new Vector2(x, y);
  2617. };
  2618. /**
  2619. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  2620. */
  2621. Vector2.Transform = function (vector, transformation) {
  2622. var r = Vector2.Zero();
  2623. Vector2.TransformToRef(vector, transformation, r);
  2624. return r;
  2625. };
  2626. /**
  2627. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  2628. */
  2629. Vector2.TransformToRef = function (vector, transformation, result) {
  2630. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2631. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2632. result.x = x;
  2633. result.y = y;
  2634. };
  2635. /**
  2636. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2637. */
  2638. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2639. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2640. var sign = a < 0 ? -1 : 1;
  2641. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2642. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2643. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2644. };
  2645. /**
  2646. * Returns the distance (float) between the vectors "value1" and "value2".
  2647. */
  2648. Vector2.Distance = function (value1, value2) {
  2649. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2650. };
  2651. /**
  2652. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2653. */
  2654. Vector2.DistanceSquared = function (value1, value2) {
  2655. var x = value1.x - value2.x;
  2656. var y = value1.y - value2.y;
  2657. return (x * x) + (y * y);
  2658. };
  2659. /**
  2660. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  2661. */
  2662. Vector2.Center = function (value1, value2) {
  2663. var center = value1.add(value2);
  2664. center.scaleInPlace(0.5);
  2665. return center;
  2666. };
  2667. /**
  2668. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2669. */
  2670. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2671. var l2 = Vector2.DistanceSquared(segA, segB);
  2672. if (l2 === 0.0) {
  2673. return Vector2.Distance(p, segA);
  2674. }
  2675. var v = segB.subtract(segA);
  2676. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2677. var proj = segA.add(v.multiplyByFloats(t, t));
  2678. return Vector2.Distance(p, proj);
  2679. };
  2680. return Vector2;
  2681. }());
  2682. BABYLON.Vector2 = Vector2;
  2683. /**
  2684. * Classed used to store (x,y,z) vector representation
  2685. * A Vector3 is the main object used in 3D geometry
  2686. * It can represent etiher the coordinates of a point the space, either a direction
  2687. * Reminder: Babylon.js uses a left handed forward facing system
  2688. */
  2689. var Vector3 = /** @class */ (function () {
  2690. /**
  2691. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  2692. * @param x defines the first coordinates (on X axis)
  2693. * @param y defines the second coordinates (on Y axis)
  2694. * @param z defines the third coordinates (on Z axis)
  2695. */
  2696. function Vector3(
  2697. /**
  2698. * Defines the first coordinates (on X axis)
  2699. */
  2700. x,
  2701. /**
  2702. * Defines the second coordinates (on Y axis)
  2703. */
  2704. y,
  2705. /**
  2706. * Defines the third coordinates (on Z axis)
  2707. */
  2708. z) {
  2709. this.x = x;
  2710. this.y = y;
  2711. this.z = z;
  2712. }
  2713. /**
  2714. * Creates a string representation of the Vector3
  2715. * @returns a string with the Vector3 coordinates.
  2716. */
  2717. Vector3.prototype.toString = function () {
  2718. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2719. };
  2720. /**
  2721. * Gets the class name
  2722. * @returns the string "Vector3"
  2723. */
  2724. Vector3.prototype.getClassName = function () {
  2725. return "Vector3";
  2726. };
  2727. /**
  2728. * Creates the Vector3 hash code
  2729. * @returns a number which tends to be unique between Vector3 instances
  2730. */
  2731. Vector3.prototype.getHashCode = function () {
  2732. var hash = this.x || 0;
  2733. hash = (hash * 397) ^ (this.y || 0);
  2734. hash = (hash * 397) ^ (this.z || 0);
  2735. return hash;
  2736. };
  2737. // Operators
  2738. /**
  2739. * Creates an array containing three elements : the coordinates of the Vector3
  2740. * @returns a new array of numbers
  2741. */
  2742. Vector3.prototype.asArray = function () {
  2743. var result = [];
  2744. this.toArray(result, 0);
  2745. return result;
  2746. };
  2747. /**
  2748. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3
  2749. * @param array defines the destination array
  2750. * @param index defines the offset in the destination array
  2751. * @returns the current Vector3
  2752. */
  2753. Vector3.prototype.toArray = function (array, index) {
  2754. if (index === void 0) { index = 0; }
  2755. array[index] = this.x;
  2756. array[index + 1] = this.y;
  2757. array[index + 2] = this.z;
  2758. return this;
  2759. };
  2760. /**
  2761. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2762. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2763. */
  2764. Vector3.prototype.toQuaternion = function () {
  2765. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  2766. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  2767. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  2768. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  2769. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  2770. var cosy = Math.cos(this.y * 0.5);
  2771. var siny = Math.sin(this.y * 0.5);
  2772. result.x = coszMinusx * siny;
  2773. result.y = -sinzMinusx * siny;
  2774. result.z = sinxPlusz * cosy;
  2775. result.w = cosxPlusz * cosy;
  2776. return result;
  2777. };
  2778. /**
  2779. * Adds the passed vector to the current Vector3
  2780. * @param otherVector defines the second operand
  2781. * @returns the current updated Vector3
  2782. */
  2783. Vector3.prototype.addInPlace = function (otherVector) {
  2784. this.x += otherVector.x;
  2785. this.y += otherVector.y;
  2786. this.z += otherVector.z;
  2787. return this;
  2788. };
  2789. /**
  2790. * Gets a new Vector3, result of the addition the current Vector3 and the passed vector
  2791. * @param otherVector defines the second operand
  2792. * @returns the resulting Vector3
  2793. */
  2794. Vector3.prototype.add = function (otherVector) {
  2795. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2796. };
  2797. /**
  2798. * Adds the current Vector3 to the passed one and stores the result in the vector "result"
  2799. * @param otherVector defines the second operand
  2800. * @param result defines the Vector3 object where to store the result
  2801. * @returns the current Vector3
  2802. */
  2803. Vector3.prototype.addToRef = function (otherVector, result) {
  2804. result.x = this.x + otherVector.x;
  2805. result.y = this.y + otherVector.y;
  2806. result.z = this.z + otherVector.z;
  2807. return this;
  2808. };
  2809. /**
  2810. * Subtract the passed vector from the current Vector3
  2811. * @param otherVector defines the second operand
  2812. * @returns the current updated Vector3
  2813. */
  2814. Vector3.prototype.subtractInPlace = function (otherVector) {
  2815. this.x -= otherVector.x;
  2816. this.y -= otherVector.y;
  2817. this.z -= otherVector.z;
  2818. return this;
  2819. };
  2820. /**
  2821. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3
  2822. * @param otherVector defines the second operand
  2823. * @returns the resulting Vector3
  2824. */
  2825. Vector3.prototype.subtract = function (otherVector) {
  2826. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2827. };
  2828. /**
  2829. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  2830. * @param otherVector defines the second operand
  2831. * @param result defines the Vector3 object where to store the result
  2832. * @returns the current Vector3
  2833. */
  2834. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2835. result.x = this.x - otherVector.x;
  2836. result.y = this.y - otherVector.y;
  2837. result.z = this.z - otherVector.z;
  2838. return this;
  2839. };
  2840. /**
  2841. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates
  2842. * @param x defines the x coordinate of the operand
  2843. * @param y defines the y coordinate of the operand
  2844. * @param z defines the z coordinate of the operand
  2845. * @returns the resulting Vector3
  2846. */
  2847. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2848. return new Vector3(this.x - x, this.y - y, this.z - z);
  2849. };
  2850. /**
  2851. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result
  2852. * @param x defines the x coordinate of the operand
  2853. * @param y defines the y coordinate of the operand
  2854. * @param z defines the z coordinate of the operand
  2855. * @param result defines the Vector3 object where to store the result
  2856. * @returns the current Vector3
  2857. */
  2858. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2859. result.x = this.x - x;
  2860. result.y = this.y - y;
  2861. result.z = this.z - z;
  2862. return this;
  2863. };
  2864. /**
  2865. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2866. * @returns a new Vector3
  2867. */
  2868. Vector3.prototype.negate = function () {
  2869. return new Vector3(-this.x, -this.y, -this.z);
  2870. };
  2871. /**
  2872. * Multiplies the Vector3 coordinates by the float "scale"
  2873. * @param scale defines the multiplier factor
  2874. * @returns the current updated Vector3
  2875. */
  2876. Vector3.prototype.scaleInPlace = function (scale) {
  2877. this.x *= scale;
  2878. this.y *= scale;
  2879. this.z *= scale;
  2880. return this;
  2881. };
  2882. /**
  2883. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2884. * @param scale defines the multiplier factor
  2885. * @returns a new Vector3
  2886. */
  2887. Vector3.prototype.scale = function (scale) {
  2888. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2889. };
  2890. /**
  2891. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates
  2892. * @param scale defines the multiplier factor
  2893. * @param result defines the Vector3 object where to store the result
  2894. * @returns the current Vector3
  2895. */
  2896. Vector3.prototype.scaleToRef = function (scale, result) {
  2897. result.x = this.x * scale;
  2898. result.y = this.y * scale;
  2899. result.z = this.z * scale;
  2900. return this;
  2901. };
  2902. /**
  2903. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2904. * @param scale defines the scale factor
  2905. * @param result defines the Vector3 object where to store the result
  2906. * @returns the unmodified current Vector3
  2907. */
  2908. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2909. result.x += this.x * scale;
  2910. result.y += this.y * scale;
  2911. result.z += this.z * scale;
  2912. return this;
  2913. };
  2914. /**
  2915. * Returns true if the current Vector3 and the passed vector coordinates are strictly equal
  2916. * @param otherVector defines the second operand
  2917. * @returns true if both vectors are equals
  2918. */
  2919. Vector3.prototype.equals = function (otherVector) {
  2920. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2921. };
  2922. /**
  2923. * Returns true if the current Vector3 and the passed vector coordinates are distant less than epsilon
  2924. * @param otherVector defines the second operand
  2925. * @param epsilon defines the minimal distance to define values as equals
  2926. * @returns true if both vectors are distant less than epsilon
  2927. */
  2928. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2929. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2930. 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);
  2931. };
  2932. /**
  2933. * Returns true if the current Vector3 coordinates equals the passed floats
  2934. * @param x defines the x coordinate of the operand
  2935. * @param y defines the y coordinate of the operand
  2936. * @param z defines the z coordinate of the operand
  2937. * @returns true if both vectors are equals
  2938. */
  2939. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2940. return this.x === x && this.y === y && this.z === z;
  2941. };
  2942. /**
  2943. * Multiplies the current Vector3 coordinates by the passed ones
  2944. * @param otherVector defines the second operand
  2945. * @returns the current updated Vector3
  2946. */
  2947. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2948. this.x *= otherVector.x;
  2949. this.y *= otherVector.y;
  2950. this.z *= otherVector.z;
  2951. return this;
  2952. };
  2953. /**
  2954. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector
  2955. * @param otherVector defines the second operand
  2956. * @returns the new Vector3
  2957. */
  2958. Vector3.prototype.multiply = function (otherVector) {
  2959. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2960. };
  2961. /**
  2962. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result"
  2963. * @param otherVector defines the second operand
  2964. * @param result defines the Vector3 object where to store the result
  2965. * @returns the current Vector3
  2966. */
  2967. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  2968. result.x = this.x * otherVector.x;
  2969. result.y = this.y * otherVector.y;
  2970. result.z = this.z * otherVector.z;
  2971. return this;
  2972. };
  2973. /**
  2974. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the passed floats
  2975. * @param x defines the x coordinate of the operand
  2976. * @param y defines the y coordinate of the operand
  2977. * @param z defines the z coordinate of the operand
  2978. * @returns the new Vector3
  2979. */
  2980. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  2981. return new Vector3(this.x * x, this.y * y, this.z * z);
  2982. };
  2983. /**
  2984. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the passed ones
  2985. * @param otherVector defines the second operand
  2986. * @returns the new Vector3
  2987. */
  2988. Vector3.prototype.divide = function (otherVector) {
  2989. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  2990. };
  2991. /**
  2992. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result"
  2993. * @param otherVector defines the second operand
  2994. * @param result defines the Vector3 object where to store the result
  2995. * @returns the current Vector3
  2996. */
  2997. Vector3.prototype.divideToRef = function (otherVector, result) {
  2998. result.x = this.x / otherVector.x;
  2999. result.y = this.y / otherVector.y;
  3000. result.z = this.z / otherVector.z;
  3001. return this;
  3002. };
  3003. /**
  3004. * Divides the current Vector3 coordinates by the passed ones.
  3005. * @param otherVector defines the second operand
  3006. * @returns the current updated Vector3
  3007. */
  3008. Vector3.prototype.divideInPlace = function (otherVector) {
  3009. return this.divideToRef(otherVector, this);
  3010. };
  3011. /**
  3012. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones
  3013. * @param other defines the second operand
  3014. * @returns the current updated Vector3
  3015. */
  3016. Vector3.prototype.minimizeInPlace = function (other) {
  3017. if (other.x < this.x)
  3018. this.x = other.x;
  3019. if (other.y < this.y)
  3020. this.y = other.y;
  3021. if (other.z < this.z)
  3022. this.z = other.z;
  3023. return this;
  3024. };
  3025. /**
  3026. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  3027. * @param other defines the second operand
  3028. * @returns the current updated Vector3
  3029. */
  3030. Vector3.prototype.maximizeInPlace = function (other) {
  3031. if (other.x > this.x)
  3032. this.x = other.x;
  3033. if (other.y > this.y)
  3034. this.y = other.y;
  3035. if (other.z > this.z)
  3036. this.z = other.z;
  3037. return this;
  3038. };
  3039. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3040. /**
  3041. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3042. */
  3043. get: function () {
  3044. var absX = Math.abs(this.x);
  3045. var absY = Math.abs(this.y);
  3046. if (absX !== absY) {
  3047. return true;
  3048. }
  3049. var absZ = Math.abs(this.z);
  3050. if (absX !== absZ) {
  3051. return true;
  3052. }
  3053. if (absY !== absZ) {
  3054. return true;
  3055. }
  3056. return false;
  3057. },
  3058. enumerable: true,
  3059. configurable: true
  3060. });
  3061. // Properties
  3062. /**
  3063. * Gets the length of the Vector3
  3064. * @returns the length of the Vecto3
  3065. */
  3066. Vector3.prototype.length = function () {
  3067. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3068. };
  3069. /**
  3070. * Gets the squared length of the Vector3
  3071. * @returns squared length of the Vector3
  3072. */
  3073. Vector3.prototype.lengthSquared = function () {
  3074. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3075. };
  3076. /**
  3077. * Normalize the current Vector3.
  3078. * Please note that this is an in place operation.
  3079. * @returns the current updated Vector3
  3080. */
  3081. Vector3.prototype.normalize = function () {
  3082. var len = this.length();
  3083. if (len === 0 || len === 1.0)
  3084. return this;
  3085. var num = 1.0 / len;
  3086. this.x *= num;
  3087. this.y *= num;
  3088. this.z *= num;
  3089. return this;
  3090. };
  3091. /**
  3092. * Normalize the current Vector3 to a new vector
  3093. * @returns the new Vector3
  3094. */
  3095. Vector3.prototype.normalizeToNew = function () {
  3096. var normalized = new Vector3(0, 0, 0);
  3097. this.normalizeToRef(normalized);
  3098. return normalized;
  3099. };
  3100. /**
  3101. * Normalize the current Vector3 to the reference
  3102. * @param reference define the Vector3 to update
  3103. * @returns the updated Vector3
  3104. */
  3105. Vector3.prototype.normalizeToRef = function (reference) {
  3106. var len = this.length();
  3107. if (len === 0 || len === 1.0) {
  3108. reference.set(this.x, this.y, this.z);
  3109. return reference;
  3110. }
  3111. var scale = 1.0 / len;
  3112. this.scaleToRef(scale, reference);
  3113. return reference;
  3114. };
  3115. /**
  3116. * Creates a new Vector3 copied from the current Vector3
  3117. * @returns the new Vector3
  3118. */
  3119. Vector3.prototype.clone = function () {
  3120. return new Vector3(this.x, this.y, this.z);
  3121. };
  3122. /**
  3123. * Copies the passed vector coordinates to the current Vector3 ones
  3124. * @param source defines the source Vector3
  3125. * @returns the current updated Vector3
  3126. */
  3127. Vector3.prototype.copyFrom = function (source) {
  3128. this.x = source.x;
  3129. this.y = source.y;
  3130. this.z = source.z;
  3131. return this;
  3132. };
  3133. /**
  3134. * Copies the passed floats to the current Vector3 coordinates
  3135. * @param x defines the x coordinate of the operand
  3136. * @param y defines the y coordinate of the operand
  3137. * @param z defines the z coordinate of the operand
  3138. * @returns the current updated Vector3
  3139. */
  3140. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3141. this.x = x;
  3142. this.y = y;
  3143. this.z = z;
  3144. return this;
  3145. };
  3146. /**
  3147. * Copies the passed floats to the current Vector3 coordinates
  3148. * @param x defines the x coordinate of the operand
  3149. * @param y defines the y coordinate of the operand
  3150. * @param z defines the z coordinate of the operand
  3151. * @returns the current updated Vector3
  3152. */
  3153. Vector3.prototype.set = function (x, y, z) {
  3154. return this.copyFromFloats(x, y, z);
  3155. };
  3156. // Statics
  3157. /**
  3158. * Get the clip factor between two vectors
  3159. * @param vector0 defines the first operand
  3160. * @param vector1 defines the second operand
  3161. * @param axis defines the axis to use
  3162. * @param size defines the size along the axis
  3163. * @returns the clip factor
  3164. */
  3165. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3166. var d0 = Vector3.Dot(vector0, axis) - size;
  3167. var d1 = Vector3.Dot(vector1, axis) - size;
  3168. var s = d0 / (d0 - d1);
  3169. return s;
  3170. };
  3171. /**
  3172. * Get angle between two vectors
  3173. * @param vector0 angle between vector0 and vector1
  3174. * @param vector1 angle between vector0 and vector1
  3175. * @param normal direction of the normal
  3176. * @return the angle between vector0 and vector1
  3177. */
  3178. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3179. var v0 = vector0.clone().normalize();
  3180. var v1 = vector1.clone().normalize();
  3181. var dot = Vector3.Dot(v0, v1);
  3182. var n = Vector3.Cross(v0, v1);
  3183. if (Vector3.Dot(n, normal) > 0) {
  3184. return Math.acos(dot);
  3185. }
  3186. return -Math.acos(dot);
  3187. };
  3188. /**
  3189. * Returns a new Vector3 set from the index "offset" of the passed array
  3190. * @param array defines the source array
  3191. * @param offset defines the offset in the source array
  3192. * @returns the new Vector3
  3193. */
  3194. Vector3.FromArray = function (array, offset) {
  3195. if (!offset) {
  3196. offset = 0;
  3197. }
  3198. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3199. };
  3200. /**
  3201. * Returns a new Vector3 set from the index "offset" of the passed Float32Array
  3202. * This function is deprecated. Use FromArray instead
  3203. * @param array defines the source array
  3204. * @param offset defines the offset in the source array
  3205. * @returns the new Vector3
  3206. */
  3207. Vector3.FromFloatArray = function (array, offset) {
  3208. return Vector3.FromArray(array, offset);
  3209. };
  3210. /**
  3211. * Sets the passed vector "result" with the element values from the index "offset" of the passed array
  3212. * @param array defines the source array
  3213. * @param offset defines the offset in the source array
  3214. * @param result defines the Vector3 where to store the result
  3215. */
  3216. Vector3.FromArrayToRef = function (array, offset, result) {
  3217. result.x = array[offset];
  3218. result.y = array[offset + 1];
  3219. result.z = array[offset + 2];
  3220. };
  3221. /**
  3222. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array
  3223. * This function is deprecated. Use FromArrayToRef instead.
  3224. * @param array defines the source array
  3225. * @param offset defines the offset in the source array
  3226. * @param result defines the Vector3 where to store the result
  3227. */
  3228. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3229. return Vector3.FromArrayToRef(array, offset, result);
  3230. };
  3231. /**
  3232. * Sets the passed vector "result" with the passed floats.
  3233. * @param x defines the x coordinate of the source
  3234. * @param y defines the y coordinate of the source
  3235. * @param z defines the z coordinate of the source
  3236. * @param result defines the Vector3 where to store the result
  3237. */
  3238. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3239. result.x = x;
  3240. result.y = y;
  3241. result.z = z;
  3242. };
  3243. /**
  3244. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3245. * @returns a new empty Vector3
  3246. */
  3247. Vector3.Zero = function () {
  3248. return new Vector3(0.0, 0.0, 0.0);
  3249. };
  3250. /**
  3251. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3252. * @returns a new unit Vector3
  3253. */
  3254. Vector3.One = function () {
  3255. return new Vector3(1.0, 1.0, 1.0);
  3256. };
  3257. /**
  3258. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3259. * @returns a new up Vector3
  3260. */
  3261. Vector3.Up = function () {
  3262. return new Vector3(0.0, 1.0, 0.0);
  3263. };
  3264. /**
  3265. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3266. * @returns a new forward Vector3
  3267. */
  3268. Vector3.Forward = function () {
  3269. return new Vector3(0.0, 0.0, 1.0);
  3270. };
  3271. /**
  3272. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3273. * @returns a new right Vector3
  3274. */
  3275. Vector3.Right = function () {
  3276. return new Vector3(1.0, 0.0, 0.0);
  3277. };
  3278. /**
  3279. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3280. * @returns a new left Vector3
  3281. */
  3282. Vector3.Left = function () {
  3283. return new Vector3(-1.0, 0.0, 0.0);
  3284. };
  3285. /**
  3286. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  3287. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3288. * @param vector defines the Vector3 to transform
  3289. * @param transformation defines the transformation matrix
  3290. * @returns the transformed Vector3
  3291. */
  3292. Vector3.TransformCoordinates = function (vector, transformation) {
  3293. var result = Vector3.Zero();
  3294. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3295. return result;
  3296. };
  3297. /**
  3298. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector
  3299. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3300. * @param vector defines the Vector3 to transform
  3301. * @param transformation defines the transformation matrix
  3302. * @param result defines the Vector3 where to store the result
  3303. */
  3304. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3305. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3306. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3307. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3308. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3309. result.x = x / w;
  3310. result.y = y / w;
  3311. result.z = z / w;
  3312. };
  3313. /**
  3314. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z)
  3315. * This method computes tranformed coordinates only, not transformed direction vectors
  3316. * @param x define the x coordinate of the source vector
  3317. * @param y define the y coordinate of the source vector
  3318. * @param z define the z coordinate of the source vector
  3319. * @param transformation defines the transformation matrix
  3320. * @param result defines the Vector3 where to store the result
  3321. */
  3322. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3323. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3324. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3325. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3326. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3327. result.x = rx / rw;
  3328. result.y = ry / rw;
  3329. result.z = rz / rw;
  3330. };
  3331. /**
  3332. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector
  3333. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3334. * @param vector defines the Vector3 to transform
  3335. * @param transformation defines the transformation matrix
  3336. * @returns the new Vector3
  3337. */
  3338. Vector3.TransformNormal = function (vector, transformation) {
  3339. var result = Vector3.Zero();
  3340. Vector3.TransformNormalToRef(vector, transformation, result);
  3341. return result;
  3342. };
  3343. /**
  3344. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector
  3345. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3346. * @param vector defines the Vector3 to transform
  3347. * @param transformation defines the transformation matrix
  3348. * @param result defines the Vector3 where to store the result
  3349. */
  3350. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3351. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3352. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3353. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3354. result.x = x;
  3355. result.y = y;
  3356. result.z = z;
  3357. };
  3358. /**
  3359. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z)
  3360. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3361. * @param x define the x coordinate of the source vector
  3362. * @param y define the y coordinate of the source vector
  3363. * @param z define the z coordinate of the source vector
  3364. * @param transformation defines the transformation matrix
  3365. * @param result defines the Vector3 where to store the result
  3366. */
  3367. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3368. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3369. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3370. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3371. };
  3372. /**
  3373. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3374. * @param value1 defines the first control point
  3375. * @param value2 defines the second control point
  3376. * @param value3 defines the third control point
  3377. * @param value4 defines the fourth control point
  3378. * @param amount defines the amount on the spline to use
  3379. * @returns the new Vector3
  3380. */
  3381. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3382. var squared = amount * amount;
  3383. var cubed = amount * squared;
  3384. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3385. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3386. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3387. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3388. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3389. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3390. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3391. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3392. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3393. return new Vector3(x, y, z);
  3394. };
  3395. /**
  3396. * 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"
  3397. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3398. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3399. * @param value defines the current value
  3400. * @param min defines the lower range value
  3401. * @param max defines the upper range value
  3402. * @returns the new Vector3
  3403. */
  3404. Vector3.Clamp = function (value, min, max) {
  3405. var x = value.x;
  3406. x = (x > max.x) ? max.x : x;
  3407. x = (x < min.x) ? min.x : x;
  3408. var y = value.y;
  3409. y = (y > max.y) ? max.y : y;
  3410. y = (y < min.y) ? min.y : y;
  3411. var z = value.z;
  3412. z = (z > max.z) ? max.z : z;
  3413. z = (z < min.z) ? min.z : z;
  3414. return new Vector3(x, y, z);
  3415. };
  3416. /**
  3417. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3418. * @param value1 defines the first control point
  3419. * @param tangent1 defines the first tangent vector
  3420. * @param value2 defines the second control point
  3421. * @param tangent2 defines the second tangent vector
  3422. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3423. * @returns the new Vector3
  3424. */
  3425. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3426. var squared = amount * amount;
  3427. var cubed = amount * squared;
  3428. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3429. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3430. var part3 = (cubed - (2.0 * squared)) + amount;
  3431. var part4 = cubed - squared;
  3432. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3433. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3434. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3435. return new Vector3(x, y, z);
  3436. };
  3437. /**
  3438. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3439. * @param start defines the start value
  3440. * @param end defines the end value
  3441. * @param amount max defines amount between both (between 0 and 1)
  3442. * @returns the new Vector3
  3443. */
  3444. Vector3.Lerp = function (start, end, amount) {
  3445. var result = new Vector3(0, 0, 0);
  3446. Vector3.LerpToRef(start, end, amount, result);
  3447. return result;
  3448. };
  3449. /**
  3450. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3451. * @param start defines the start value
  3452. * @param end defines the end value
  3453. * @param amount max defines amount between both (between 0 and 1)
  3454. * @param result defines the Vector3 where to store the result
  3455. */
  3456. Vector3.LerpToRef = function (start, end, amount, result) {
  3457. result.x = start.x + ((end.x - start.x) * amount);
  3458. result.y = start.y + ((end.y - start.y) * amount);
  3459. result.z = start.z + ((end.z - start.z) * amount);
  3460. };
  3461. /**
  3462. * Returns the dot product (float) between the vectors "left" and "right"
  3463. * @param left defines the left operand
  3464. * @param right defines the right operand
  3465. * @returns the dot product
  3466. */
  3467. Vector3.Dot = function (left, right) {
  3468. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3469. };
  3470. /**
  3471. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3472. * The cross product is then orthogonal to both "left" and "right"
  3473. * @param left defines the left operand
  3474. * @param right defines the right operand
  3475. * @returns the cross product
  3476. */
  3477. Vector3.Cross = function (left, right) {
  3478. var result = Vector3.Zero();
  3479. Vector3.CrossToRef(left, right, result);
  3480. return result;
  3481. };
  3482. /**
  3483. * Sets the passed vector "result" with the cross product of "left" and "right"
  3484. * The cross product is then orthogonal to both "left" and "right"
  3485. * @param left defines the left operand
  3486. * @param right defines the right operand
  3487. * @param result defines the Vector3 where to store the result
  3488. */
  3489. Vector3.CrossToRef = function (left, right, result) {
  3490. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3491. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3492. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3493. result.copyFrom(MathTmp.Vector3[0]);
  3494. };
  3495. /**
  3496. * Returns a new Vector3 as the normalization of the passed vector
  3497. * @param vector defines the Vector3 to normalize
  3498. * @returns the new Vector3
  3499. */
  3500. Vector3.Normalize = function (vector) {
  3501. var result = Vector3.Zero();
  3502. Vector3.NormalizeToRef(vector, result);
  3503. return result;
  3504. };
  3505. /**
  3506. * Sets the passed vector "result" with the normalization of the passed first vector
  3507. * @param vector defines the Vector3 to normalize
  3508. * @param result defines the Vector3 where to store the result
  3509. */
  3510. Vector3.NormalizeToRef = function (vector, result) {
  3511. result.copyFrom(vector);
  3512. result.normalize();
  3513. };
  3514. /**
  3515. * Project a Vector3 onto screen space
  3516. * @param vector defines the Vector3 to project
  3517. * @param world defines the world matrix to use
  3518. * @param transform defines the transform (view x projection) matrix to use
  3519. * @param viewport defines the screen viewport to use
  3520. * @returns the new Vector3
  3521. */
  3522. Vector3.Project = function (vector, world, transform, viewport) {
  3523. var cw = viewport.width;
  3524. var ch = viewport.height;
  3525. var cx = viewport.x;
  3526. var cy = viewport.y;
  3527. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3528. 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);
  3529. var matrix = MathTmp.Matrix[0];
  3530. world.multiplyToRef(transform, matrix);
  3531. matrix.multiplyToRef(viewportMatrix, matrix);
  3532. return Vector3.TransformCoordinates(vector, matrix);
  3533. };
  3534. /**
  3535. * Unproject from screen space to object space
  3536. * @param source defines the screen space Vector3 to use
  3537. * @param viewportWidth defines the current width of the viewport
  3538. * @param viewportHeight defines the current height of the viewport
  3539. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3540. * @param transform defines the transform (view x projection) matrix to use
  3541. * @returns the new Vector3
  3542. */
  3543. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3544. var matrix = MathTmp.Matrix[0];
  3545. world.multiplyToRef(transform, matrix);
  3546. matrix.invert();
  3547. source.x = source.x / viewportWidth * 2 - 1;
  3548. source.y = -(source.y / viewportHeight * 2 - 1);
  3549. var vector = Vector3.TransformCoordinates(source, matrix);
  3550. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3551. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3552. vector = vector.scale(1.0 / num);
  3553. }
  3554. return vector;
  3555. };
  3556. /**
  3557. * Unproject from screen space to object space
  3558. * @param source defines the screen space Vector3 to use
  3559. * @param viewportWidth defines the current width of the viewport
  3560. * @param viewportHeight defines the current height of the viewport
  3561. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3562. * @param view defines the view matrix to use
  3563. * @param projection defines the projection matrix to use
  3564. * @returns the new Vector3
  3565. */
  3566. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3567. var result = Vector3.Zero();
  3568. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3569. return result;
  3570. };
  3571. /**
  3572. * Unproject from screen space to object space
  3573. * @param source defines the screen space Vector3 to use
  3574. * @param viewportWidth defines the current width of the viewport
  3575. * @param viewportHeight defines the current height of the viewport
  3576. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3577. * @param view defines the view matrix to use
  3578. * @param projection defines the projection matrix to use
  3579. * @param result defines the Vector3 where to store the result
  3580. */
  3581. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3582. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3583. };
  3584. /**
  3585. * Unproject from screen space to object space
  3586. * @param sourceX defines the screen space x coordinate to use
  3587. * @param sourceY defines the screen space y coordinate to use
  3588. * @param sourceZ defines the screen space z coordinate to use
  3589. * @param viewportWidth defines the current width of the viewport
  3590. * @param viewportHeight defines the current height of the viewport
  3591. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3592. * @param view defines the view matrix to use
  3593. * @param projection defines the projection matrix to use
  3594. * @param result defines the Vector3 where to store the result
  3595. */
  3596. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3597. var matrix = MathTmp.Matrix[0];
  3598. world.multiplyToRef(view, matrix);
  3599. matrix.multiplyToRef(projection, matrix);
  3600. matrix.invert();
  3601. var screenSource = MathTmp.Vector3[0];
  3602. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3603. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3604. screenSource.z = 2 * sourceZ - 1.0;
  3605. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3606. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3607. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3608. result.scaleInPlace(1.0 / num);
  3609. }
  3610. };
  3611. /**
  3612. * Gets the minimal coordinate values between two Vector3
  3613. * @param left defines the first operand
  3614. * @param right defines the second operand
  3615. * @returns the new Vector3
  3616. */
  3617. Vector3.Minimize = function (left, right) {
  3618. var min = left.clone();
  3619. min.minimizeInPlace(right);
  3620. return min;
  3621. };
  3622. /**
  3623. * Gets the maximal coordinate values between two Vector3
  3624. * @param left defines the first operand
  3625. * @param right defines the second operand
  3626. * @returns the new Vector3
  3627. */
  3628. Vector3.Maximize = function (left, right) {
  3629. var max = left.clone();
  3630. max.maximizeInPlace(right);
  3631. return max;
  3632. };
  3633. /**
  3634. * Returns the distance between the vectors "value1" and "value2"
  3635. * @param value1 defines the first operand
  3636. * @param value2 defines the second operand
  3637. * @returns the distance
  3638. */
  3639. Vector3.Distance = function (value1, value2) {
  3640. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3641. };
  3642. /**
  3643. * Returns the squared distance between the vectors "value1" and "value2"
  3644. * @param value1 defines the first operand
  3645. * @param value2 defines the second operand
  3646. * @returns the squared distance
  3647. */
  3648. Vector3.DistanceSquared = function (value1, value2) {
  3649. var x = value1.x - value2.x;
  3650. var y = value1.y - value2.y;
  3651. var z = value1.z - value2.z;
  3652. return (x * x) + (y * y) + (z * z);
  3653. };
  3654. /**
  3655. * Returns a new Vector3 located at the center between "value1" and "value2"
  3656. * @param value1 defines the first operand
  3657. * @param value2 defines the second operand
  3658. * @returns the new Vector3
  3659. */
  3660. Vector3.Center = function (value1, value2) {
  3661. var center = value1.add(value2);
  3662. center.scaleInPlace(0.5);
  3663. return center;
  3664. };
  3665. /**
  3666. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3667. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3668. * to something in order to rotate it from its local system to the given target system
  3669. * Note: axis1, axis2 and axis3 are normalized during this operation
  3670. * @param axis1 defines the first axis
  3671. * @param axis2 defines the second axis
  3672. * @param axis3 defines the third axis
  3673. * @returns a new Vector3
  3674. */
  3675. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3676. var rotation = Vector3.Zero();
  3677. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3678. return rotation;
  3679. };
  3680. /**
  3681. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3
  3682. * @param axis1 defines the first axis
  3683. * @param axis2 defines the second axis
  3684. * @param axis3 defines the third axis
  3685. * @param ref defines the Vector3 where to store the result
  3686. */
  3687. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3688. var quat = MathTmp.Quaternion[0];
  3689. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3690. quat.toEulerAnglesToRef(ref);
  3691. };
  3692. return Vector3;
  3693. }());
  3694. BABYLON.Vector3 = Vector3;
  3695. //Vector4 class created for EulerAngle class conversion to Quaternion
  3696. var Vector4 = /** @class */ (function () {
  3697. /**
  3698. * Creates a Vector4 object from the passed floats.
  3699. */
  3700. function Vector4(x, y, z, w) {
  3701. this.x = x;
  3702. this.y = y;
  3703. this.z = z;
  3704. this.w = w;
  3705. }
  3706. /**
  3707. * Returns the string with the Vector4 coordinates.
  3708. */
  3709. Vector4.prototype.toString = function () {
  3710. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3711. };
  3712. /**
  3713. * Returns the string "Vector4".
  3714. */
  3715. Vector4.prototype.getClassName = function () {
  3716. return "Vector4";
  3717. };
  3718. /**
  3719. * Returns the Vector4 hash code.
  3720. */
  3721. Vector4.prototype.getHashCode = function () {
  3722. var hash = this.x || 0;
  3723. hash = (hash * 397) ^ (this.y || 0);
  3724. hash = (hash * 397) ^ (this.z || 0);
  3725. hash = (hash * 397) ^ (this.w || 0);
  3726. return hash;
  3727. };
  3728. // Operators
  3729. /**
  3730. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3731. */
  3732. Vector4.prototype.asArray = function () {
  3733. var result = new Array();
  3734. this.toArray(result, 0);
  3735. return result;
  3736. };
  3737. /**
  3738. * Populates the passed array from the passed index with the Vector4 coordinates.
  3739. * Returns the Vector4.
  3740. */
  3741. Vector4.prototype.toArray = function (array, index) {
  3742. if (index === undefined) {
  3743. index = 0;
  3744. }
  3745. array[index] = this.x;
  3746. array[index + 1] = this.y;
  3747. array[index + 2] = this.z;
  3748. array[index + 3] = this.w;
  3749. return this;
  3750. };
  3751. /**
  3752. * Adds the passed vector to the current Vector4.
  3753. * Returns the updated Vector4.
  3754. */
  3755. Vector4.prototype.addInPlace = function (otherVector) {
  3756. this.x += otherVector.x;
  3757. this.y += otherVector.y;
  3758. this.z += otherVector.z;
  3759. this.w += otherVector.w;
  3760. return this;
  3761. };
  3762. /**
  3763. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  3764. */
  3765. Vector4.prototype.add = function (otherVector) {
  3766. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3767. };
  3768. /**
  3769. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  3770. * Returns the current Vector4.
  3771. */
  3772. Vector4.prototype.addToRef = function (otherVector, result) {
  3773. result.x = this.x + otherVector.x;
  3774. result.y = this.y + otherVector.y;
  3775. result.z = this.z + otherVector.z;
  3776. result.w = this.w + otherVector.w;
  3777. return this;
  3778. };
  3779. /**
  3780. * Subtract in place the passed vector from the current Vector4.
  3781. * Returns the updated Vector4.
  3782. */
  3783. Vector4.prototype.subtractInPlace = function (otherVector) {
  3784. this.x -= otherVector.x;
  3785. this.y -= otherVector.y;
  3786. this.z -= otherVector.z;
  3787. this.w -= otherVector.w;
  3788. return this;
  3789. };
  3790. /**
  3791. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  3792. */
  3793. Vector4.prototype.subtract = function (otherVector) {
  3794. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3795. };
  3796. /**
  3797. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  3798. * Returns the current Vector4.
  3799. */
  3800. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3801. result.x = this.x - otherVector.x;
  3802. result.y = this.y - otherVector.y;
  3803. result.z = this.z - otherVector.z;
  3804. result.w = this.w - otherVector.w;
  3805. return this;
  3806. };
  3807. /**
  3808. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3809. */
  3810. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3811. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3812. };
  3813. /**
  3814. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  3815. * Returns the current Vector4.
  3816. */
  3817. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3818. result.x = this.x - x;
  3819. result.y = this.y - y;
  3820. result.z = this.z - z;
  3821. result.w = this.w - w;
  3822. return this;
  3823. };
  3824. /**
  3825. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3826. */
  3827. Vector4.prototype.negate = function () {
  3828. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3829. };
  3830. /**
  3831. * Multiplies the current Vector4 coordinates by scale (float).
  3832. * Returns the updated Vector4.
  3833. */
  3834. Vector4.prototype.scaleInPlace = function (scale) {
  3835. this.x *= scale;
  3836. this.y *= scale;
  3837. this.z *= scale;
  3838. this.w *= scale;
  3839. return this;
  3840. };
  3841. /**
  3842. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3843. */
  3844. Vector4.prototype.scale = function (scale) {
  3845. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3846. };
  3847. /**
  3848. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3849. * Returns the current Vector4.
  3850. */
  3851. Vector4.prototype.scaleToRef = function (scale, result) {
  3852. result.x = this.x * scale;
  3853. result.y = this.y * scale;
  3854. result.z = this.z * scale;
  3855. result.w = this.w * scale;
  3856. return this;
  3857. };
  3858. /**
  3859. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3860. * @param scale defines the scale factor
  3861. * @param result defines the Vector4 object where to store the result
  3862. * @returns the unmodified current Vector4
  3863. */
  3864. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3865. result.x += this.x * scale;
  3866. result.y += this.y * scale;
  3867. result.z += this.z * scale;
  3868. result.w += this.w * scale;
  3869. return this;
  3870. };
  3871. /**
  3872. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  3873. */
  3874. Vector4.prototype.equals = function (otherVector) {
  3875. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3876. };
  3877. /**
  3878. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  3879. */
  3880. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3881. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3882. return otherVector
  3883. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3884. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3885. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3886. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3887. };
  3888. /**
  3889. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  3890. */
  3891. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3892. return this.x === x && this.y === y && this.z === z && this.w === w;
  3893. };
  3894. /**
  3895. * Multiplies in place the current Vector4 by the passed one.
  3896. * Returns the updated Vector4.
  3897. */
  3898. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3899. this.x *= otherVector.x;
  3900. this.y *= otherVector.y;
  3901. this.z *= otherVector.z;
  3902. this.w *= otherVector.w;
  3903. return this;
  3904. };
  3905. /**
  3906. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  3907. */
  3908. Vector4.prototype.multiply = function (otherVector) {
  3909. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3910. };
  3911. /**
  3912. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  3913. * Returns the current Vector4.
  3914. */
  3915. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3916. result.x = this.x * otherVector.x;
  3917. result.y = this.y * otherVector.y;
  3918. result.z = this.z * otherVector.z;
  3919. result.w = this.w * otherVector.w;
  3920. return this;
  3921. };
  3922. /**
  3923. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  3924. */
  3925. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3926. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3927. };
  3928. /**
  3929. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  3930. */
  3931. Vector4.prototype.divide = function (otherVector) {
  3932. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3933. };
  3934. /**
  3935. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  3936. * Returns the current Vector4.
  3937. */
  3938. Vector4.prototype.divideToRef = function (otherVector, result) {
  3939. result.x = this.x / otherVector.x;
  3940. result.y = this.y / otherVector.y;
  3941. result.z = this.z / otherVector.z;
  3942. result.w = this.w / otherVector.w;
  3943. return this;
  3944. };
  3945. /**
  3946. * Divides the current Vector3 coordinates by the passed ones.
  3947. * @returns the updated Vector3.
  3948. */
  3949. Vector4.prototype.divideInPlace = function (otherVector) {
  3950. return this.divideToRef(otherVector, this);
  3951. };
  3952. /**
  3953. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones
  3954. * @param other defines the second operand
  3955. * @returns the current updated Vector4
  3956. */
  3957. Vector4.prototype.minimizeInPlace = function (other) {
  3958. if (other.x < this.x)
  3959. this.x = other.x;
  3960. if (other.y < this.y)
  3961. this.y = other.y;
  3962. if (other.z < this.z)
  3963. this.z = other.z;
  3964. if (other.w < this.w)
  3965. this.w = other.w;
  3966. return this;
  3967. };
  3968. /**
  3969. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones
  3970. * @param other defines the second operand
  3971. * @returns the current updated Vector4
  3972. */
  3973. Vector4.prototype.maximizeInPlace = function (other) {
  3974. if (other.x > this.x)
  3975. this.x = other.x;
  3976. if (other.y > this.y)
  3977. this.y = other.y;
  3978. if (other.z > this.z)
  3979. this.z = other.z;
  3980. if (other.w > this.w)
  3981. this.w = other.w;
  3982. return this;
  3983. };
  3984. // Properties
  3985. /**
  3986. * Returns the Vector4 length (float).
  3987. */
  3988. Vector4.prototype.length = function () {
  3989. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3990. };
  3991. /**
  3992. * Returns the Vector4 squared length (float).
  3993. */
  3994. Vector4.prototype.lengthSquared = function () {
  3995. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  3996. };
  3997. // Methods
  3998. /**
  3999. * Normalizes in place the Vector4.
  4000. * Returns the updated Vector4.
  4001. */
  4002. Vector4.prototype.normalize = function () {
  4003. var len = this.length();
  4004. if (len === 0)
  4005. return this;
  4006. var num = 1.0 / len;
  4007. this.x *= num;
  4008. this.y *= num;
  4009. this.z *= num;
  4010. this.w *= num;
  4011. return this;
  4012. };
  4013. /**
  4014. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4015. */
  4016. Vector4.prototype.toVector3 = function () {
  4017. return new Vector3(this.x, this.y, this.z);
  4018. };
  4019. /**
  4020. * Returns a new Vector4 copied from the current one.
  4021. */
  4022. Vector4.prototype.clone = function () {
  4023. return new Vector4(this.x, this.y, this.z, this.w);
  4024. };
  4025. /**
  4026. * Updates the current Vector4 with the passed one coordinates.
  4027. * Returns the updated Vector4.
  4028. */
  4029. Vector4.prototype.copyFrom = function (source) {
  4030. this.x = source.x;
  4031. this.y = source.y;
  4032. this.z = source.z;
  4033. this.w = source.w;
  4034. return this;
  4035. };
  4036. /**
  4037. * Updates the current Vector4 coordinates with the passed floats.
  4038. * Returns the updated Vector4.
  4039. */
  4040. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4041. this.x = x;
  4042. this.y = y;
  4043. this.z = z;
  4044. this.w = w;
  4045. return this;
  4046. };
  4047. /**
  4048. * Updates the current Vector4 coordinates with the passed floats.
  4049. * Returns the updated Vector4.
  4050. */
  4051. Vector4.prototype.set = function (x, y, z, w) {
  4052. return this.copyFromFloats(x, y, z, w);
  4053. };
  4054. // Statics
  4055. /**
  4056. * Returns a new Vector4 set from the starting index of the passed array.
  4057. */
  4058. Vector4.FromArray = function (array, offset) {
  4059. if (!offset) {
  4060. offset = 0;
  4061. }
  4062. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4063. };
  4064. /**
  4065. * Updates the passed vector "result" from the starting index of the passed array.
  4066. */
  4067. Vector4.FromArrayToRef = function (array, offset, result) {
  4068. result.x = array[offset];
  4069. result.y = array[offset + 1];
  4070. result.z = array[offset + 2];
  4071. result.w = array[offset + 3];
  4072. };
  4073. /**
  4074. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  4075. */
  4076. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4077. Vector4.FromArrayToRef(array, offset, result);
  4078. };
  4079. /**
  4080. * Updates the passed vector "result" coordinates from the passed floats.
  4081. */
  4082. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4083. result.x = x;
  4084. result.y = y;
  4085. result.z = z;
  4086. result.w = w;
  4087. };
  4088. /**
  4089. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4090. */
  4091. Vector4.Zero = function () {
  4092. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4093. };
  4094. /**
  4095. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4096. */
  4097. Vector4.One = function () {
  4098. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4099. };
  4100. /**
  4101. * Returns a new normalized Vector4 from the passed one.
  4102. */
  4103. Vector4.Normalize = function (vector) {
  4104. var result = Vector4.Zero();
  4105. Vector4.NormalizeToRef(vector, result);
  4106. return result;
  4107. };
  4108. /**
  4109. * Updates the passed vector "result" from the normalization of the passed one.
  4110. */
  4111. Vector4.NormalizeToRef = function (vector, result) {
  4112. result.copyFrom(vector);
  4113. result.normalize();
  4114. };
  4115. Vector4.Minimize = function (left, right) {
  4116. var min = left.clone();
  4117. min.minimizeInPlace(right);
  4118. return min;
  4119. };
  4120. Vector4.Maximize = function (left, right) {
  4121. var max = left.clone();
  4122. max.maximizeInPlace(right);
  4123. return max;
  4124. };
  4125. /**
  4126. * Returns the distance (float) between the vectors "value1" and "value2".
  4127. */
  4128. Vector4.Distance = function (value1, value2) {
  4129. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4130. };
  4131. /**
  4132. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4133. */
  4134. Vector4.DistanceSquared = function (value1, value2) {
  4135. var x = value1.x - value2.x;
  4136. var y = value1.y - value2.y;
  4137. var z = value1.z - value2.z;
  4138. var w = value1.w - value2.w;
  4139. return (x * x) + (y * y) + (z * z) + (w * w);
  4140. };
  4141. /**
  4142. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4143. */
  4144. Vector4.Center = function (value1, value2) {
  4145. var center = value1.add(value2);
  4146. center.scaleInPlace(0.5);
  4147. return center;
  4148. };
  4149. /**
  4150. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  4151. * This methods computes transformed normalized direction vectors only.
  4152. */
  4153. Vector4.TransformNormal = function (vector, transformation) {
  4154. var result = Vector4.Zero();
  4155. Vector4.TransformNormalToRef(vector, transformation, result);
  4156. return result;
  4157. };
  4158. /**
  4159. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  4160. * This methods computes transformed normalized direction vectors only.
  4161. */
  4162. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4163. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4164. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4165. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4166. result.x = x;
  4167. result.y = y;
  4168. result.z = z;
  4169. result.w = vector.w;
  4170. };
  4171. /**
  4172. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  4173. * This methods computes transformed normalized direction vectors only.
  4174. */
  4175. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4176. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4177. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4178. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4179. result.w = w;
  4180. };
  4181. return Vector4;
  4182. }());
  4183. BABYLON.Vector4 = Vector4;
  4184. var Size = /** @class */ (function () {
  4185. /**
  4186. * Creates a Size object from the passed width and height (floats).
  4187. */
  4188. function Size(width, height) {
  4189. this.width = width;
  4190. this.height = height;
  4191. }
  4192. // Returns a string with the Size width and height.
  4193. Size.prototype.toString = function () {
  4194. return "{W: " + this.width + ", H: " + this.height + "}";
  4195. };
  4196. /**
  4197. * Returns the string "Size"
  4198. */
  4199. Size.prototype.getClassName = function () {
  4200. return "Size";
  4201. };
  4202. /**
  4203. * Returns the Size hash code.
  4204. */
  4205. Size.prototype.getHashCode = function () {
  4206. var hash = this.width || 0;
  4207. hash = (hash * 397) ^ (this.height || 0);
  4208. return hash;
  4209. };
  4210. /**
  4211. * Updates the current size from the passed one.
  4212. * Returns the updated Size.
  4213. */
  4214. Size.prototype.copyFrom = function (src) {
  4215. this.width = src.width;
  4216. this.height = src.height;
  4217. };
  4218. /**
  4219. * Updates in place the current Size from the passed floats.
  4220. * Returns the updated Size.
  4221. */
  4222. Size.prototype.copyFromFloats = function (width, height) {
  4223. this.width = width;
  4224. this.height = height;
  4225. return this;
  4226. };
  4227. /**
  4228. * Updates in place the current Size from the passed floats.
  4229. * Returns the updated Size.
  4230. */
  4231. Size.prototype.set = function (width, height) {
  4232. return this.copyFromFloats(width, height);
  4233. };
  4234. /**
  4235. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  4236. */
  4237. Size.prototype.multiplyByFloats = function (w, h) {
  4238. return new Size(this.width * w, this.height * h);
  4239. };
  4240. /**
  4241. * Returns a new Size copied from the passed one.
  4242. */
  4243. Size.prototype.clone = function () {
  4244. return new Size(this.width, this.height);
  4245. };
  4246. /**
  4247. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  4248. */
  4249. Size.prototype.equals = function (other) {
  4250. if (!other) {
  4251. return false;
  4252. }
  4253. return (this.width === other.width) && (this.height === other.height);
  4254. };
  4255. Object.defineProperty(Size.prototype, "surface", {
  4256. /**
  4257. * Returns the surface of the Size : width * height (float).
  4258. */
  4259. get: function () {
  4260. return this.width * this.height;
  4261. },
  4262. enumerable: true,
  4263. configurable: true
  4264. });
  4265. /**
  4266. * Returns a new Size set to (0.0, 0.0)
  4267. */
  4268. Size.Zero = function () {
  4269. return new Size(0.0, 0.0);
  4270. };
  4271. /**
  4272. * Returns a new Size set as the addition result of the current Size and the passed one.
  4273. */
  4274. Size.prototype.add = function (otherSize) {
  4275. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4276. return r;
  4277. };
  4278. /**
  4279. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  4280. */
  4281. Size.prototype.subtract = function (otherSize) {
  4282. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4283. return r;
  4284. };
  4285. /**
  4286. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4287. */
  4288. Size.Lerp = function (start, end, amount) {
  4289. var w = start.width + ((end.width - start.width) * amount);
  4290. var h = start.height + ((end.height - start.height) * amount);
  4291. return new Size(w, h);
  4292. };
  4293. return Size;
  4294. }());
  4295. BABYLON.Size = Size;
  4296. var Quaternion = /** @class */ (function () {
  4297. /**
  4298. * Creates a new Quaternion from the passed floats.
  4299. */
  4300. function Quaternion(x, y, z, w) {
  4301. if (x === void 0) { x = 0.0; }
  4302. if (y === void 0) { y = 0.0; }
  4303. if (z === void 0) { z = 0.0; }
  4304. if (w === void 0) { w = 1.0; }
  4305. this.x = x;
  4306. this.y = y;
  4307. this.z = z;
  4308. this.w = w;
  4309. }
  4310. /**
  4311. * Returns a string with the Quaternion coordinates.
  4312. */
  4313. Quaternion.prototype.toString = function () {
  4314. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4315. };
  4316. /**
  4317. * Returns the string "Quaternion".
  4318. */
  4319. Quaternion.prototype.getClassName = function () {
  4320. return "Quaternion";
  4321. };
  4322. /**
  4323. * Returns the Quaternion hash code.
  4324. */
  4325. Quaternion.prototype.getHashCode = function () {
  4326. var hash = this.x || 0;
  4327. hash = (hash * 397) ^ (this.y || 0);
  4328. hash = (hash * 397) ^ (this.z || 0);
  4329. hash = (hash * 397) ^ (this.w || 0);
  4330. return hash;
  4331. };
  4332. /**
  4333. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  4334. */
  4335. Quaternion.prototype.asArray = function () {
  4336. return [this.x, this.y, this.z, this.w];
  4337. };
  4338. /**
  4339. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  4340. */
  4341. Quaternion.prototype.equals = function (otherQuaternion) {
  4342. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4343. };
  4344. /**
  4345. * Returns a new Quaternion copied from the current one.
  4346. */
  4347. Quaternion.prototype.clone = function () {
  4348. return new Quaternion(this.x, this.y, this.z, this.w);
  4349. };
  4350. /**
  4351. * Updates the current Quaternion from the passed one coordinates.
  4352. * Returns the updated Quaterion.
  4353. */
  4354. Quaternion.prototype.copyFrom = function (other) {
  4355. this.x = other.x;
  4356. this.y = other.y;
  4357. this.z = other.z;
  4358. this.w = other.w;
  4359. return this;
  4360. };
  4361. /**
  4362. * Updates the current Quaternion from the passed float coordinates.
  4363. * Returns the updated Quaterion.
  4364. */
  4365. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4366. this.x = x;
  4367. this.y = y;
  4368. this.z = z;
  4369. this.w = w;
  4370. return this;
  4371. };
  4372. /**
  4373. * Updates the current Quaternion from the passed float coordinates.
  4374. * Returns the updated Quaterion.
  4375. */
  4376. Quaternion.prototype.set = function (x, y, z, w) {
  4377. return this.copyFromFloats(x, y, z, w);
  4378. };
  4379. /**
  4380. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  4381. */
  4382. Quaternion.prototype.add = function (other) {
  4383. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4384. };
  4385. /**
  4386. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  4387. */
  4388. Quaternion.prototype.subtract = function (other) {
  4389. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4390. };
  4391. /**
  4392. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  4393. */
  4394. Quaternion.prototype.scale = function (value) {
  4395. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4396. };
  4397. /**
  4398. * Scale the current Quaternion values by a factor to a given Quaternion
  4399. * @param scale defines the scale factor
  4400. * @param result defines the Quaternion object where to store the result
  4401. * @returns the unmodified current Quaternion
  4402. */
  4403. Quaternion.prototype.scaleToRef = function (scale, result) {
  4404. result.x = this.x * scale;
  4405. result.y = this.y * scale;
  4406. result.z = this.z * scale;
  4407. result.w = this.w * scale;
  4408. return this;
  4409. };
  4410. /**
  4411. * Scale the current Quaternion values by a factor and add the result to a given Quaternion
  4412. * @param scale defines the scale factor
  4413. * @param result defines the Quaternion object where to store the result
  4414. * @returns the unmodified current Quaternion
  4415. */
  4416. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4417. result.x += this.x * scale;
  4418. result.y += this.y * scale;
  4419. result.z += this.z * scale;
  4420. result.w += this.w * scale;
  4421. return this;
  4422. };
  4423. /**
  4424. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  4425. */
  4426. Quaternion.prototype.multiply = function (q1) {
  4427. var result = new Quaternion(0, 0, 0, 1.0);
  4428. this.multiplyToRef(q1, result);
  4429. return result;
  4430. };
  4431. /**
  4432. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  4433. * Returns the current Quaternion.
  4434. */
  4435. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4436. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4437. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4438. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4439. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4440. result.copyFromFloats(x, y, z, w);
  4441. return this;
  4442. };
  4443. /**
  4444. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  4445. * Returns the updated Quaternion.
  4446. */
  4447. Quaternion.prototype.multiplyInPlace = function (q1) {
  4448. this.multiplyToRef(q1, this);
  4449. return this;
  4450. };
  4451. /**
  4452. * Sets the passed "ref" with the conjugation of the current Quaternion.
  4453. * Returns the current Quaternion.
  4454. */
  4455. Quaternion.prototype.conjugateToRef = function (ref) {
  4456. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4457. return this;
  4458. };
  4459. /**
  4460. * Conjugates in place the current Quaternion.
  4461. * Returns the updated Quaternion.
  4462. */
  4463. Quaternion.prototype.conjugateInPlace = function () {
  4464. this.x *= -1;
  4465. this.y *= -1;
  4466. this.z *= -1;
  4467. return this;
  4468. };
  4469. /**
  4470. * Returns a new Quaternion as the conjugate of the current Quaternion.
  4471. */
  4472. Quaternion.prototype.conjugate = function () {
  4473. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4474. return result;
  4475. };
  4476. /**
  4477. * Returns the Quaternion length (float).
  4478. */
  4479. Quaternion.prototype.length = function () {
  4480. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4481. };
  4482. /**
  4483. * Normalize in place the current Quaternion.
  4484. * Returns the updated Quaternion.
  4485. */
  4486. Quaternion.prototype.normalize = function () {
  4487. var length = 1.0 / this.length();
  4488. this.x *= length;
  4489. this.y *= length;
  4490. this.z *= length;
  4491. this.w *= length;
  4492. return this;
  4493. };
  4494. /**
  4495. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion
  4496. * @param order is a reserved parameter and is ignore for now
  4497. * @returns the new Vector3
  4498. */
  4499. Quaternion.prototype.toEulerAngles = function (order) {
  4500. if (order === void 0) { order = "YZX"; }
  4501. var result = Vector3.Zero();
  4502. this.toEulerAnglesToRef(result, order);
  4503. return result;
  4504. };
  4505. /**
  4506. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion
  4507. * @param result defines the vector which will be filled with the Euler angles
  4508. * @param order is a reserved parameter and is ignore for now
  4509. * @returns the current Quaternion
  4510. */
  4511. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4512. if (order === void 0) { order = "YZX"; }
  4513. var qz = this.z;
  4514. var qx = this.x;
  4515. var qy = this.y;
  4516. var qw = this.w;
  4517. var sqw = qw * qw;
  4518. var sqz = qz * qz;
  4519. var sqx = qx * qx;
  4520. var sqy = qy * qy;
  4521. var zAxisY = qy * qz - qx * qw;
  4522. var limit = .4999999;
  4523. if (zAxisY < -limit) {
  4524. result.y = 2 * Math.atan2(qy, qw);
  4525. result.x = Math.PI / 2;
  4526. result.z = 0;
  4527. }
  4528. else if (zAxisY > limit) {
  4529. result.y = 2 * Math.atan2(qy, qw);
  4530. result.x = -Math.PI / 2;
  4531. result.z = 0;
  4532. }
  4533. else {
  4534. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4535. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4536. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4537. }
  4538. return this;
  4539. };
  4540. /**
  4541. * Updates the passed rotation matrix with the current Quaternion values.
  4542. * Returns the current Quaternion.
  4543. */
  4544. Quaternion.prototype.toRotationMatrix = function (result) {
  4545. var xx = this.x * this.x;
  4546. var yy = this.y * this.y;
  4547. var zz = this.z * this.z;
  4548. var xy = this.x * this.y;
  4549. var zw = this.z * this.w;
  4550. var zx = this.z * this.x;
  4551. var yw = this.y * this.w;
  4552. var yz = this.y * this.z;
  4553. var xw = this.x * this.w;
  4554. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4555. result.m[1] = 2.0 * (xy + zw);
  4556. result.m[2] = 2.0 * (zx - yw);
  4557. result.m[3] = 0;
  4558. result.m[4] = 2.0 * (xy - zw);
  4559. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4560. result.m[6] = 2.0 * (yz + xw);
  4561. result.m[7] = 0;
  4562. result.m[8] = 2.0 * (zx + yw);
  4563. result.m[9] = 2.0 * (yz - xw);
  4564. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4565. result.m[11] = 0;
  4566. result.m[12] = 0;
  4567. result.m[13] = 0;
  4568. result.m[14] = 0;
  4569. result.m[15] = 1.0;
  4570. result._markAsUpdated();
  4571. return this;
  4572. };
  4573. /**
  4574. * Updates the current Quaternion from the passed rotation matrix values.
  4575. * Returns the updated Quaternion.
  4576. */
  4577. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4578. Quaternion.FromRotationMatrixToRef(matrix, this);
  4579. return this;
  4580. };
  4581. // Statics
  4582. /**
  4583. * Returns a new Quaternion set from the passed rotation matrix values.
  4584. */
  4585. Quaternion.FromRotationMatrix = function (matrix) {
  4586. var result = new Quaternion();
  4587. Quaternion.FromRotationMatrixToRef(matrix, result);
  4588. return result;
  4589. };
  4590. /**
  4591. * Updates the passed quaternion "result" with the passed rotation matrix values.
  4592. */
  4593. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4594. var data = matrix.m;
  4595. var m11 = data[0], m12 = data[4], m13 = data[8];
  4596. var m21 = data[1], m22 = data[5], m23 = data[9];
  4597. var m31 = data[2], m32 = data[6], m33 = data[10];
  4598. var trace = m11 + m22 + m33;
  4599. var s;
  4600. if (trace > 0) {
  4601. s = 0.5 / Math.sqrt(trace + 1.0);
  4602. result.w = 0.25 / s;
  4603. result.x = (m32 - m23) * s;
  4604. result.y = (m13 - m31) * s;
  4605. result.z = (m21 - m12) * s;
  4606. }
  4607. else if (m11 > m22 && m11 > m33) {
  4608. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4609. result.w = (m32 - m23) / s;
  4610. result.x = 0.25 * s;
  4611. result.y = (m12 + m21) / s;
  4612. result.z = (m13 + m31) / s;
  4613. }
  4614. else if (m22 > m33) {
  4615. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4616. result.w = (m13 - m31) / s;
  4617. result.x = (m12 + m21) / s;
  4618. result.y = 0.25 * s;
  4619. result.z = (m23 + m32) / s;
  4620. }
  4621. else {
  4622. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4623. result.w = (m21 - m12) / s;
  4624. result.x = (m13 + m31) / s;
  4625. result.y = (m23 + m32) / s;
  4626. result.z = 0.25 * s;
  4627. }
  4628. };
  4629. /**
  4630. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  4631. */
  4632. Quaternion.Zero = function () {
  4633. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4634. };
  4635. /**
  4636. * Returns a new Quaternion as the inverted current Quaternion.
  4637. */
  4638. Quaternion.Inverse = function (q) {
  4639. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4640. };
  4641. /**
  4642. * Returns the identity Quaternion.
  4643. */
  4644. Quaternion.Identity = function () {
  4645. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4646. };
  4647. Quaternion.IsIdentity = function (quaternion) {
  4648. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4649. };
  4650. /**
  4651. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  4652. */
  4653. Quaternion.RotationAxis = function (axis, angle) {
  4654. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4655. };
  4656. /**
  4657. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  4658. */
  4659. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4660. var sin = Math.sin(angle / 2);
  4661. axis.normalize();
  4662. result.w = Math.cos(angle / 2);
  4663. result.x = axis.x * sin;
  4664. result.y = axis.y * sin;
  4665. result.z = axis.z * sin;
  4666. return result;
  4667. };
  4668. /**
  4669. * Retuns a new Quaternion set from the starting index of the passed array.
  4670. */
  4671. Quaternion.FromArray = function (array, offset) {
  4672. if (!offset) {
  4673. offset = 0;
  4674. }
  4675. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4676. };
  4677. /**
  4678. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  4679. */
  4680. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4681. var q = new Quaternion();
  4682. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4683. return q;
  4684. };
  4685. /**
  4686. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  4687. */
  4688. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4689. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4690. var halfRoll = roll * 0.5;
  4691. var halfPitch = pitch * 0.5;
  4692. var halfYaw = yaw * 0.5;
  4693. var sinRoll = Math.sin(halfRoll);
  4694. var cosRoll = Math.cos(halfRoll);
  4695. var sinPitch = Math.sin(halfPitch);
  4696. var cosPitch = Math.cos(halfPitch);
  4697. var sinYaw = Math.sin(halfYaw);
  4698. var cosYaw = Math.cos(halfYaw);
  4699. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4700. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4701. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4702. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4703. };
  4704. /**
  4705. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  4706. */
  4707. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4708. var result = new Quaternion();
  4709. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4710. return result;
  4711. };
  4712. /**
  4713. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  4714. */
  4715. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4716. // Produces a quaternion from Euler angles in the z-x-z orientation
  4717. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4718. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4719. var halfBeta = beta * 0.5;
  4720. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4721. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4722. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4723. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4724. };
  4725. /**
  4726. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4727. * cf to Vector3.RotationFromAxis() documentation.
  4728. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4729. */
  4730. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  4731. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4732. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4733. return quat;
  4734. };
  4735. /**
  4736. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  4737. * cf to Vector3.RotationFromAxis() documentation.
  4738. * Note : axis1, axis2 and axis3 are normalized during this operation.
  4739. */
  4740. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4741. var rotMat = MathTmp.Matrix[0];
  4742. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4743. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4744. };
  4745. Quaternion.Slerp = function (left, right, amount) {
  4746. var result = Quaternion.Identity();
  4747. Quaternion.SlerpToRef(left, right, amount, result);
  4748. return result;
  4749. };
  4750. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4751. var num2;
  4752. var num3;
  4753. var num = amount;
  4754. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4755. var flag = false;
  4756. if (num4 < 0) {
  4757. flag = true;
  4758. num4 = -num4;
  4759. }
  4760. if (num4 > 0.999999) {
  4761. num3 = 1 - num;
  4762. num2 = flag ? -num : num;
  4763. }
  4764. else {
  4765. var num5 = Math.acos(num4);
  4766. var num6 = (1.0 / Math.sin(num5));
  4767. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  4768. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  4769. }
  4770. result.x = (num3 * left.x) + (num2 * right.x);
  4771. result.y = (num3 * left.y) + (num2 * right.y);
  4772. result.z = (num3 * left.z) + (num2 * right.z);
  4773. result.w = (num3 * left.w) + (num2 * right.w);
  4774. };
  4775. /**
  4776. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  4777. */
  4778. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4779. var squared = amount * amount;
  4780. var cubed = amount * squared;
  4781. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4782. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4783. var part3 = (cubed - (2.0 * squared)) + amount;
  4784. var part4 = cubed - squared;
  4785. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4786. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4787. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4788. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4789. return new Quaternion(x, y, z, w);
  4790. };
  4791. return Quaternion;
  4792. }());
  4793. BABYLON.Quaternion = Quaternion;
  4794. var Matrix = /** @class */ (function () {
  4795. function Matrix() {
  4796. this._isIdentity = false;
  4797. this._isIdentityDirty = true;
  4798. this.m = new Float32Array(16);
  4799. this._markAsUpdated();
  4800. }
  4801. Matrix.prototype._markAsUpdated = function () {
  4802. this.updateFlag = Matrix._updateFlagSeed++;
  4803. this._isIdentityDirty = true;
  4804. };
  4805. // Properties
  4806. /**
  4807. * Boolean : True is the matrix is the identity matrix
  4808. */
  4809. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  4810. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  4811. if (this._isIdentityDirty) {
  4812. this._isIdentityDirty = false;
  4813. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  4814. this._isIdentity = false;
  4815. }
  4816. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  4817. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  4818. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  4819. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  4820. this._isIdentity = false;
  4821. }
  4822. else {
  4823. this._isIdentity = true;
  4824. }
  4825. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  4826. this._isIdentity = false;
  4827. }
  4828. }
  4829. return this._isIdentity;
  4830. };
  4831. /**
  4832. * Returns the matrix determinant (float).
  4833. */
  4834. Matrix.prototype.determinant = function () {
  4835. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  4836. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  4837. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  4838. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  4839. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  4840. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  4841. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  4842. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  4843. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  4844. };
  4845. // Methods
  4846. /**
  4847. * Returns the matrix underlying array.
  4848. */
  4849. Matrix.prototype.toArray = function () {
  4850. return this.m;
  4851. };
  4852. /**
  4853. * Returns the matrix underlying array.
  4854. */
  4855. Matrix.prototype.asArray = function () {
  4856. return this.toArray();
  4857. };
  4858. /**
  4859. * Inverts in place the Matrix.
  4860. * Returns the Matrix inverted.
  4861. */
  4862. Matrix.prototype.invert = function () {
  4863. this.invertToRef(this);
  4864. return this;
  4865. };
  4866. /**
  4867. * Sets all the matrix elements to zero.
  4868. * Returns the Matrix.
  4869. */
  4870. Matrix.prototype.reset = function () {
  4871. for (var index = 0; index < 16; index++) {
  4872. this.m[index] = 0.0;
  4873. }
  4874. this._markAsUpdated();
  4875. return this;
  4876. };
  4877. /**
  4878. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  4879. */
  4880. Matrix.prototype.add = function (other) {
  4881. var result = new Matrix();
  4882. this.addToRef(other, result);
  4883. return result;
  4884. };
  4885. /**
  4886. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  4887. * Returns the Matrix.
  4888. */
  4889. Matrix.prototype.addToRef = function (other, result) {
  4890. for (var index = 0; index < 16; index++) {
  4891. result.m[index] = this.m[index] + other.m[index];
  4892. }
  4893. result._markAsUpdated();
  4894. return this;
  4895. };
  4896. /**
  4897. * Adds in place the passed matrix to the current Matrix.
  4898. * Returns the updated Matrix.
  4899. */
  4900. Matrix.prototype.addToSelf = function (other) {
  4901. for (var index = 0; index < 16; index++) {
  4902. this.m[index] += other.m[index];
  4903. }
  4904. this._markAsUpdated();
  4905. return this;
  4906. };
  4907. /**
  4908. * Sets the passed matrix with the current inverted Matrix.
  4909. * Returns the unmodified current Matrix.
  4910. */
  4911. Matrix.prototype.invertToRef = function (other) {
  4912. var l1 = this.m[0];
  4913. var l2 = this.m[1];
  4914. var l3 = this.m[2];
  4915. var l4 = this.m[3];
  4916. var l5 = this.m[4];
  4917. var l6 = this.m[5];
  4918. var l7 = this.m[6];
  4919. var l8 = this.m[7];
  4920. var l9 = this.m[8];
  4921. var l10 = this.m[9];
  4922. var l11 = this.m[10];
  4923. var l12 = this.m[11];
  4924. var l13 = this.m[12];
  4925. var l14 = this.m[13];
  4926. var l15 = this.m[14];
  4927. var l16 = this.m[15];
  4928. var l17 = (l11 * l16) - (l12 * l15);
  4929. var l18 = (l10 * l16) - (l12 * l14);
  4930. var l19 = (l10 * l15) - (l11 * l14);
  4931. var l20 = (l9 * l16) - (l12 * l13);
  4932. var l21 = (l9 * l15) - (l11 * l13);
  4933. var l22 = (l9 * l14) - (l10 * l13);
  4934. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  4935. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  4936. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  4937. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  4938. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  4939. var l28 = (l7 * l16) - (l8 * l15);
  4940. var l29 = (l6 * l16) - (l8 * l14);
  4941. var l30 = (l6 * l15) - (l7 * l14);
  4942. var l31 = (l5 * l16) - (l8 * l13);
  4943. var l32 = (l5 * l15) - (l7 * l13);
  4944. var l33 = (l5 * l14) - (l6 * l13);
  4945. var l34 = (l7 * l12) - (l8 * l11);
  4946. var l35 = (l6 * l12) - (l8 * l10);
  4947. var l36 = (l6 * l11) - (l7 * l10);
  4948. var l37 = (l5 * l12) - (l8 * l9);
  4949. var l38 = (l5 * l11) - (l7 * l9);
  4950. var l39 = (l5 * l10) - (l6 * l9);
  4951. other.m[0] = l23 * l27;
  4952. other.m[4] = l24 * l27;
  4953. other.m[8] = l25 * l27;
  4954. other.m[12] = l26 * l27;
  4955. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  4956. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  4957. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  4958. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  4959. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  4960. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  4961. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  4962. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  4963. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  4964. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  4965. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  4966. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  4967. other._markAsUpdated();
  4968. return this;
  4969. };
  4970. /**
  4971. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  4972. * Returns the updated Matrix.
  4973. */
  4974. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  4975. this.m[12] = x;
  4976. this.m[13] = y;
  4977. this.m[14] = z;
  4978. this._markAsUpdated();
  4979. return this;
  4980. };
  4981. /**
  4982. * Inserts the translation vector in the current Matrix.
  4983. * Returns the updated Matrix.
  4984. */
  4985. Matrix.prototype.setTranslation = function (vector3) {
  4986. this.m[12] = vector3.x;
  4987. this.m[13] = vector3.y;
  4988. this.m[14] = vector3.z;
  4989. this._markAsUpdated();
  4990. return this;
  4991. };
  4992. /**
  4993. * Returns a new Vector3 as the extracted translation from the Matrix.
  4994. */
  4995. Matrix.prototype.getTranslation = function () {
  4996. return new Vector3(this.m[12], this.m[13], this.m[14]);
  4997. };
  4998. /**
  4999. * Fill a Vector3 with the extracted translation from the Matrix.
  5000. */
  5001. Matrix.prototype.getTranslationToRef = function (result) {
  5002. result.x = this.m[12];
  5003. result.y = this.m[13];
  5004. result.z = this.m[14];
  5005. return this;
  5006. };
  5007. /**
  5008. * Remove rotation and scaling part from the Matrix.
  5009. * Returns the updated Matrix.
  5010. */
  5011. Matrix.prototype.removeRotationAndScaling = function () {
  5012. this.setRowFromFloats(0, 1, 0, 0, 0);
  5013. this.setRowFromFloats(1, 0, 1, 0, 0);
  5014. this.setRowFromFloats(2, 0, 0, 1, 0);
  5015. return this;
  5016. };
  5017. /**
  5018. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  5019. */
  5020. Matrix.prototype.multiply = function (other) {
  5021. var result = new Matrix();
  5022. this.multiplyToRef(other, result);
  5023. return result;
  5024. };
  5025. /**
  5026. * Updates the current Matrix from the passed one values.
  5027. * Returns the updated Matrix.
  5028. */
  5029. Matrix.prototype.copyFrom = function (other) {
  5030. for (var index = 0; index < 16; index++) {
  5031. this.m[index] = other.m[index];
  5032. }
  5033. this._markAsUpdated();
  5034. return this;
  5035. };
  5036. /**
  5037. * Populates the passed array from the starting index with the Matrix values.
  5038. * Returns the Matrix.
  5039. */
  5040. Matrix.prototype.copyToArray = function (array, offset) {
  5041. if (offset === void 0) { offset = 0; }
  5042. for (var index = 0; index < 16; index++) {
  5043. array[offset + index] = this.m[index];
  5044. }
  5045. return this;
  5046. };
  5047. /**
  5048. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  5049. */
  5050. Matrix.prototype.multiplyToRef = function (other, result) {
  5051. this.multiplyToArray(other, result.m, 0);
  5052. result._markAsUpdated();
  5053. return this;
  5054. };
  5055. /**
  5056. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  5057. */
  5058. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5059. var tm0 = this.m[0];
  5060. var tm1 = this.m[1];
  5061. var tm2 = this.m[2];
  5062. var tm3 = this.m[3];
  5063. var tm4 = this.m[4];
  5064. var tm5 = this.m[5];
  5065. var tm6 = this.m[6];
  5066. var tm7 = this.m[7];
  5067. var tm8 = this.m[8];
  5068. var tm9 = this.m[9];
  5069. var tm10 = this.m[10];
  5070. var tm11 = this.m[11];
  5071. var tm12 = this.m[12];
  5072. var tm13 = this.m[13];
  5073. var tm14 = this.m[14];
  5074. var tm15 = this.m[15];
  5075. var om0 = other.m[0];
  5076. var om1 = other.m[1];
  5077. var om2 = other.m[2];
  5078. var om3 = other.m[3];
  5079. var om4 = other.m[4];
  5080. var om5 = other.m[5];
  5081. var om6 = other.m[6];
  5082. var om7 = other.m[7];
  5083. var om8 = other.m[8];
  5084. var om9 = other.m[9];
  5085. var om10 = other.m[10];
  5086. var om11 = other.m[11];
  5087. var om12 = other.m[12];
  5088. var om13 = other.m[13];
  5089. var om14 = other.m[14];
  5090. var om15 = other.m[15];
  5091. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5092. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5093. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5094. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5095. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5096. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5097. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5098. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5099. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5100. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5101. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5102. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5103. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5104. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5105. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5106. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5107. return this;
  5108. };
  5109. /**
  5110. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  5111. */
  5112. Matrix.prototype.equals = function (value) {
  5113. return value &&
  5114. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5115. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5116. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5117. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5118. };
  5119. /**
  5120. * Returns a new Matrix from the current Matrix.
  5121. */
  5122. Matrix.prototype.clone = function () {
  5123. 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]);
  5124. };
  5125. /**
  5126. * Returns the string "Matrix"
  5127. */
  5128. Matrix.prototype.getClassName = function () {
  5129. return "Matrix";
  5130. };
  5131. /**
  5132. * Returns the Matrix hash code.
  5133. */
  5134. Matrix.prototype.getHashCode = function () {
  5135. var hash = this.m[0] || 0;
  5136. for (var i = 1; i < 16; i++) {
  5137. hash = (hash * 397) ^ (this.m[i] || 0);
  5138. }
  5139. return hash;
  5140. };
  5141. /**
  5142. * Decomposes the current Matrix into :
  5143. * - a scale vector3 passed as a reference to update,
  5144. * - a rotation quaternion passed as a reference to update,
  5145. * - a translation vector3 passed as a reference to update.
  5146. * Returns the true if operation was successful.
  5147. */
  5148. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5149. translation.x = this.m[12];
  5150. translation.y = this.m[13];
  5151. translation.z = this.m[14];
  5152. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5153. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5154. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5155. if (this.determinant() <= 0) {
  5156. scale.y *= -1;
  5157. }
  5158. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5159. rotation.x = 0;
  5160. rotation.y = 0;
  5161. rotation.z = 0;
  5162. rotation.w = 1;
  5163. return false;
  5164. }
  5165. 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]);
  5166. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5167. return true;
  5168. };
  5169. /**
  5170. * Returns the index-th row of the current matrix as a new Vector4.
  5171. */
  5172. Matrix.prototype.getRow = function (index) {
  5173. if (index < 0 || index > 3) {
  5174. return null;
  5175. }
  5176. var i = index * 4;
  5177. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5178. };
  5179. /**
  5180. * Sets the index-th row of the current matrix with the passed Vector4 values.
  5181. * Returns the updated Matrix.
  5182. */
  5183. Matrix.prototype.setRow = function (index, row) {
  5184. if (index < 0 || index > 3) {
  5185. return this;
  5186. }
  5187. var i = index * 4;
  5188. this.m[i + 0] = row.x;
  5189. this.m[i + 1] = row.y;
  5190. this.m[i + 2] = row.z;
  5191. this.m[i + 3] = row.w;
  5192. this._markAsUpdated();
  5193. return this;
  5194. };
  5195. /**
  5196. * Compute the transpose of the matrix.
  5197. * Returns a new Matrix.
  5198. */
  5199. Matrix.prototype.transpose = function () {
  5200. return Matrix.Transpose(this);
  5201. };
  5202. /**
  5203. * Compute the transpose of the matrix.
  5204. * Returns the current matrix.
  5205. */
  5206. Matrix.prototype.transposeToRef = function (result) {
  5207. Matrix.TransposeToRef(this, result);
  5208. return this;
  5209. };
  5210. /**
  5211. * Sets the index-th row of the current matrix with the passed 4 x float values.
  5212. * Returns the updated Matrix.
  5213. */
  5214. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5215. if (index < 0 || index > 3) {
  5216. return this;
  5217. }
  5218. var i = index * 4;
  5219. this.m[i + 0] = x;
  5220. this.m[i + 1] = y;
  5221. this.m[i + 2] = z;
  5222. this.m[i + 3] = w;
  5223. this._markAsUpdated();
  5224. return this;
  5225. };
  5226. /**
  5227. * Compute a new Matrix set with the current Matrix values multiplied by scale (float)
  5228. * @param scale defines the scale factor
  5229. * @returns a new Matrix
  5230. */
  5231. Matrix.prototype.scale = function (scale) {
  5232. var result = new Matrix();
  5233. this.scaleToRef(scale, result);
  5234. return result;
  5235. };
  5236. /**
  5237. * Scale the current Matrix values by a factor to a given result Matrix
  5238. * @param scale defines the scale factor
  5239. * @param result defines the Matrix to store the result
  5240. * @returns the current Matrix
  5241. */
  5242. Matrix.prototype.scaleToRef = function (scale, result) {
  5243. for (var index = 0; index < 16; index++) {
  5244. result.m[index] = this.m[index] * scale;
  5245. }
  5246. result._markAsUpdated();
  5247. return this;
  5248. };
  5249. /**
  5250. * Scale the current Matrix values by a factor and add the result to a given Matrix
  5251. * @param scale defines the scale factor
  5252. * @param result defines the Matrix to store the result
  5253. * @returns the current Matrix
  5254. */
  5255. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5256. for (var index = 0; index < 16; index++) {
  5257. result.m[index] += this.m[index] * scale;
  5258. }
  5259. result._markAsUpdated();
  5260. return this;
  5261. };
  5262. /**
  5263. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5264. * @param ref matrix to store the result
  5265. */
  5266. Matrix.prototype.toNormalMatrix = function (ref) {
  5267. this.invertToRef(ref);
  5268. ref.transpose();
  5269. var m = ref.m;
  5270. 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);
  5271. };
  5272. /**
  5273. * Returns a new Matrix as the extracted rotation matrix from the current one.
  5274. */
  5275. Matrix.prototype.getRotationMatrix = function () {
  5276. var result = Matrix.Identity();
  5277. this.getRotationMatrixToRef(result);
  5278. return result;
  5279. };
  5280. /**
  5281. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  5282. * Returns the current Matrix.
  5283. */
  5284. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5285. var m = this.m;
  5286. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  5287. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  5288. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  5289. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5290. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5291. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5292. 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);
  5293. return this;
  5294. };
  5295. // Statics
  5296. /**
  5297. * Returns a new Matrix set from the starting index of the passed array.
  5298. */
  5299. Matrix.FromArray = function (array, offset) {
  5300. var result = new Matrix();
  5301. if (!offset) {
  5302. offset = 0;
  5303. }
  5304. Matrix.FromArrayToRef(array, offset, result);
  5305. return result;
  5306. };
  5307. /**
  5308. * Sets the passed "result" matrix from the starting index of the passed array.
  5309. */
  5310. Matrix.FromArrayToRef = function (array, offset, result) {
  5311. for (var index = 0; index < 16; index++) {
  5312. result.m[index] = array[index + offset];
  5313. }
  5314. result._markAsUpdated();
  5315. };
  5316. /**
  5317. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  5318. */
  5319. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5320. for (var index = 0; index < 16; index++) {
  5321. result.m[index] = array[index + offset] * scale;
  5322. }
  5323. result._markAsUpdated();
  5324. };
  5325. /**
  5326. * Sets the passed matrix "result" with the 16 passed floats.
  5327. */
  5328. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5329. result.m[0] = initialM11;
  5330. result.m[1] = initialM12;
  5331. result.m[2] = initialM13;
  5332. result.m[3] = initialM14;
  5333. result.m[4] = initialM21;
  5334. result.m[5] = initialM22;
  5335. result.m[6] = initialM23;
  5336. result.m[7] = initialM24;
  5337. result.m[8] = initialM31;
  5338. result.m[9] = initialM32;
  5339. result.m[10] = initialM33;
  5340. result.m[11] = initialM34;
  5341. result.m[12] = initialM41;
  5342. result.m[13] = initialM42;
  5343. result.m[14] = initialM43;
  5344. result.m[15] = initialM44;
  5345. result._markAsUpdated();
  5346. };
  5347. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5348. /**
  5349. * Static identity matrix to be used as readonly matrix
  5350. * Must not be updated.
  5351. */
  5352. get: function () {
  5353. return Matrix._identityReadOnly;
  5354. },
  5355. enumerable: true,
  5356. configurable: true
  5357. });
  5358. /**
  5359. * Returns a new Matrix set from the 16 passed floats.
  5360. */
  5361. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5362. var result = new Matrix();
  5363. result.m[0] = initialM11;
  5364. result.m[1] = initialM12;
  5365. result.m[2] = initialM13;
  5366. result.m[3] = initialM14;
  5367. result.m[4] = initialM21;
  5368. result.m[5] = initialM22;
  5369. result.m[6] = initialM23;
  5370. result.m[7] = initialM24;
  5371. result.m[8] = initialM31;
  5372. result.m[9] = initialM32;
  5373. result.m[10] = initialM33;
  5374. result.m[11] = initialM34;
  5375. result.m[12] = initialM41;
  5376. result.m[13] = initialM42;
  5377. result.m[14] = initialM43;
  5378. result.m[15] = initialM44;
  5379. return result;
  5380. };
  5381. /**
  5382. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5383. */
  5384. Matrix.Compose = function (scale, rotation, translation) {
  5385. var result = Matrix.Identity();
  5386. Matrix.ComposeToRef(scale, rotation, translation, result);
  5387. return result;
  5388. };
  5389. /**
  5390. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  5391. */
  5392. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5393. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5394. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5395. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5396. result.setTranslation(translation);
  5397. };
  5398. /**
  5399. * Returns a new indentity Matrix.
  5400. */
  5401. Matrix.Identity = function () {
  5402. 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);
  5403. };
  5404. /**
  5405. * Sets the passed "result" as an identity matrix.
  5406. */
  5407. Matrix.IdentityToRef = function (result) {
  5408. 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);
  5409. };
  5410. /**
  5411. * Returns a new zero Matrix.
  5412. */
  5413. Matrix.Zero = function () {
  5414. 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);
  5415. };
  5416. /**
  5417. * Returns a new rotation matrix for "angle" radians around the X axis.
  5418. */
  5419. Matrix.RotationX = function (angle) {
  5420. var result = new Matrix();
  5421. Matrix.RotationXToRef(angle, result);
  5422. return result;
  5423. };
  5424. /**
  5425. * Returns a new Matrix as the passed inverted one.
  5426. */
  5427. Matrix.Invert = function (source) {
  5428. var result = new Matrix();
  5429. source.invertToRef(result);
  5430. return result;
  5431. };
  5432. /**
  5433. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  5434. */
  5435. Matrix.RotationXToRef = function (angle, result) {
  5436. var s = Math.sin(angle);
  5437. var c = Math.cos(angle);
  5438. result.m[0] = 1.0;
  5439. result.m[15] = 1.0;
  5440. result.m[5] = c;
  5441. result.m[10] = c;
  5442. result.m[9] = -s;
  5443. result.m[6] = s;
  5444. result.m[1] = 0.0;
  5445. result.m[2] = 0.0;
  5446. result.m[3] = 0.0;
  5447. result.m[4] = 0.0;
  5448. result.m[7] = 0.0;
  5449. result.m[8] = 0.0;
  5450. result.m[11] = 0.0;
  5451. result.m[12] = 0.0;
  5452. result.m[13] = 0.0;
  5453. result.m[14] = 0.0;
  5454. result._markAsUpdated();
  5455. };
  5456. /**
  5457. * Returns a new rotation matrix for "angle" radians around the Y axis.
  5458. */
  5459. Matrix.RotationY = function (angle) {
  5460. var result = new Matrix();
  5461. Matrix.RotationYToRef(angle, result);
  5462. return result;
  5463. };
  5464. /**
  5465. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  5466. */
  5467. Matrix.RotationYToRef = function (angle, result) {
  5468. var s = Math.sin(angle);
  5469. var c = Math.cos(angle);
  5470. result.m[5] = 1.0;
  5471. result.m[15] = 1.0;
  5472. result.m[0] = c;
  5473. result.m[2] = -s;
  5474. result.m[8] = s;
  5475. result.m[10] = c;
  5476. result.m[1] = 0.0;
  5477. result.m[3] = 0.0;
  5478. result.m[4] = 0.0;
  5479. result.m[6] = 0.0;
  5480. result.m[7] = 0.0;
  5481. result.m[9] = 0.0;
  5482. result.m[11] = 0.0;
  5483. result.m[12] = 0.0;
  5484. result.m[13] = 0.0;
  5485. result.m[14] = 0.0;
  5486. result._markAsUpdated();
  5487. };
  5488. /**
  5489. * Returns a new rotation matrix for "angle" radians around the Z axis.
  5490. */
  5491. Matrix.RotationZ = function (angle) {
  5492. var result = new Matrix();
  5493. Matrix.RotationZToRef(angle, result);
  5494. return result;
  5495. };
  5496. /**
  5497. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  5498. */
  5499. Matrix.RotationZToRef = function (angle, result) {
  5500. var s = Math.sin(angle);
  5501. var c = Math.cos(angle);
  5502. result.m[10] = 1.0;
  5503. result.m[15] = 1.0;
  5504. result.m[0] = c;
  5505. result.m[1] = s;
  5506. result.m[4] = -s;
  5507. result.m[5] = c;
  5508. result.m[2] = 0.0;
  5509. result.m[3] = 0.0;
  5510. result.m[6] = 0.0;
  5511. result.m[7] = 0.0;
  5512. result.m[8] = 0.0;
  5513. result.m[9] = 0.0;
  5514. result.m[11] = 0.0;
  5515. result.m[12] = 0.0;
  5516. result.m[13] = 0.0;
  5517. result.m[14] = 0.0;
  5518. result._markAsUpdated();
  5519. };
  5520. /**
  5521. * Returns a new rotation matrix for "angle" radians around the passed axis.
  5522. */
  5523. Matrix.RotationAxis = function (axis, angle) {
  5524. var result = Matrix.Zero();
  5525. Matrix.RotationAxisToRef(axis, angle, result);
  5526. return result;
  5527. };
  5528. /**
  5529. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  5530. */
  5531. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5532. var s = Math.sin(-angle);
  5533. var c = Math.cos(-angle);
  5534. var c1 = 1 - c;
  5535. axis.normalize();
  5536. result.m[0] = (axis.x * axis.x) * c1 + c;
  5537. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5538. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5539. result.m[3] = 0.0;
  5540. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5541. result.m[5] = (axis.y * axis.y) * c1 + c;
  5542. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5543. result.m[7] = 0.0;
  5544. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5545. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5546. result.m[10] = (axis.z * axis.z) * c1 + c;
  5547. result.m[11] = 0.0;
  5548. result.m[15] = 1.0;
  5549. result._markAsUpdated();
  5550. };
  5551. /**
  5552. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  5553. */
  5554. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5555. var result = new Matrix();
  5556. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5557. return result;
  5558. };
  5559. /**
  5560. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  5561. */
  5562. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5563. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5564. this._tempQuaternion.toRotationMatrix(result);
  5565. };
  5566. /**
  5567. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  5568. */
  5569. Matrix.Scaling = function (x, y, z) {
  5570. var result = Matrix.Zero();
  5571. Matrix.ScalingToRef(x, y, z, result);
  5572. return result;
  5573. };
  5574. /**
  5575. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  5576. */
  5577. Matrix.ScalingToRef = function (x, y, z, result) {
  5578. result.m[0] = x;
  5579. result.m[1] = 0.0;
  5580. result.m[2] = 0.0;
  5581. result.m[3] = 0.0;
  5582. result.m[4] = 0.0;
  5583. result.m[5] = y;
  5584. result.m[6] = 0.0;
  5585. result.m[7] = 0.0;
  5586. result.m[8] = 0.0;
  5587. result.m[9] = 0.0;
  5588. result.m[10] = z;
  5589. result.m[11] = 0.0;
  5590. result.m[12] = 0.0;
  5591. result.m[13] = 0.0;
  5592. result.m[14] = 0.0;
  5593. result.m[15] = 1.0;
  5594. result._markAsUpdated();
  5595. };
  5596. /**
  5597. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  5598. */
  5599. Matrix.Translation = function (x, y, z) {
  5600. var result = Matrix.Identity();
  5601. Matrix.TranslationToRef(x, y, z, result);
  5602. return result;
  5603. };
  5604. /**
  5605. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  5606. */
  5607. Matrix.TranslationToRef = function (x, y, z, result) {
  5608. 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);
  5609. };
  5610. /**
  5611. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5612. * @param startValue defines the start value
  5613. * @param endValue defines the end value
  5614. * @param gradient defines the gradient factor
  5615. * @returns the new matrix
  5616. */
  5617. Matrix.Lerp = function (startValue, endValue, gradient) {
  5618. var result = Matrix.Zero();
  5619. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5620. return result;
  5621. };
  5622. /**
  5623. * Set the passed matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5624. * @param startValue defines the start value
  5625. * @param endValue defines the end value
  5626. * @param gradient defines the gradient factor
  5627. * @param result defines the Matrix object where to store data
  5628. */
  5629. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  5630. for (var index = 0; index < 16; index++) {
  5631. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5632. }
  5633. result._markAsUpdated();
  5634. };
  5635. /**
  5636. * Returns a new Matrix whose values are computed by :
  5637. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  5638. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  5639. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  5640. */
  5641. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  5642. var startScale = new Vector3(0, 0, 0);
  5643. var startRotation = new Quaternion();
  5644. var startTranslation = new Vector3(0, 0, 0);
  5645. startValue.decompose(startScale, startRotation, startTranslation);
  5646. var endScale = new Vector3(0, 0, 0);
  5647. var endRotation = new Quaternion();
  5648. var endTranslation = new Vector3(0, 0, 0);
  5649. endValue.decompose(endScale, endRotation, endTranslation);
  5650. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  5651. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  5652. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  5653. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  5654. };
  5655. /**
  5656. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5657. * This methods works for a Left-Handed system.
  5658. */
  5659. Matrix.LookAtLH = function (eye, target, up) {
  5660. var result = Matrix.Zero();
  5661. Matrix.LookAtLHToRef(eye, target, up, result);
  5662. return result;
  5663. };
  5664. /**
  5665. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5666. * This methods works for a Left-Handed system.
  5667. */
  5668. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  5669. // Z axis
  5670. target.subtractToRef(eye, this._zAxis);
  5671. this._zAxis.normalize();
  5672. // X axis
  5673. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5674. if (this._xAxis.lengthSquared() === 0) {
  5675. this._xAxis.x = 1.0;
  5676. }
  5677. else {
  5678. this._xAxis.normalize();
  5679. }
  5680. // Y axis
  5681. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5682. this._yAxis.normalize();
  5683. // Eye angles
  5684. var ex = -Vector3.Dot(this._xAxis, eye);
  5685. var ey = -Vector3.Dot(this._yAxis, eye);
  5686. var ez = -Vector3.Dot(this._zAxis, eye);
  5687. 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);
  5688. };
  5689. /**
  5690. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5691. * This methods works for a Right-Handed system.
  5692. */
  5693. Matrix.LookAtRH = function (eye, target, up) {
  5694. var result = Matrix.Zero();
  5695. Matrix.LookAtRHToRef(eye, target, up, result);
  5696. return result;
  5697. };
  5698. /**
  5699. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  5700. * This methods works for a Left-Handed system.
  5701. */
  5702. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  5703. // Z axis
  5704. eye.subtractToRef(target, this._zAxis);
  5705. this._zAxis.normalize();
  5706. // X axis
  5707. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  5708. if (this._xAxis.lengthSquared() === 0) {
  5709. this._xAxis.x = 1.0;
  5710. }
  5711. else {
  5712. this._xAxis.normalize();
  5713. }
  5714. // Y axis
  5715. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  5716. this._yAxis.normalize();
  5717. // Eye angles
  5718. var ex = -Vector3.Dot(this._xAxis, eye);
  5719. var ey = -Vector3.Dot(this._yAxis, eye);
  5720. var ez = -Vector3.Dot(this._zAxis, eye);
  5721. 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);
  5722. };
  5723. /**
  5724. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5725. */
  5726. Matrix.OrthoLH = function (width, height, znear, zfar) {
  5727. var matrix = Matrix.Zero();
  5728. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  5729. return matrix;
  5730. };
  5731. /**
  5732. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5733. */
  5734. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  5735. var n = znear;
  5736. var f = zfar;
  5737. var a = 2.0 / width;
  5738. var b = 2.0 / height;
  5739. var c = 2.0 / (f - n);
  5740. var d = -(f + n) / (f - n);
  5741. 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);
  5742. };
  5743. /**
  5744. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5745. */
  5746. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  5747. var matrix = Matrix.Zero();
  5748. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  5749. return matrix;
  5750. };
  5751. /**
  5752. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5753. */
  5754. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5755. var n = znear;
  5756. var f = zfar;
  5757. var a = 2.0 / (right - left);
  5758. var b = 2.0 / (top - bottom);
  5759. var c = 2.0 / (f - n);
  5760. var d = -(f + n) / (f - n);
  5761. var i0 = (left + right) / (left - right);
  5762. var i1 = (top + bottom) / (bottom - top);
  5763. 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);
  5764. };
  5765. /**
  5766. * Returns a new Matrix as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5767. */
  5768. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  5769. var matrix = Matrix.Zero();
  5770. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  5771. return matrix;
  5772. };
  5773. /**
  5774. * Sets the passed matrix "result" as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  5775. */
  5776. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  5777. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  5778. result.m[10] *= -1.0;
  5779. };
  5780. /**
  5781. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  5782. */
  5783. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  5784. var matrix = Matrix.Zero();
  5785. var n = znear;
  5786. var f = zfar;
  5787. var a = 2.0 * n / width;
  5788. var b = 2.0 * n / height;
  5789. var c = (f + n) / (f - n);
  5790. var d = -2.0 * f * n / (f - n);
  5791. 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);
  5792. return matrix;
  5793. };
  5794. /**
  5795. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5796. */
  5797. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  5798. var matrix = Matrix.Zero();
  5799. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  5800. return matrix;
  5801. };
  5802. /**
  5803. * Sets the passed matrix "result" as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5804. */
  5805. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5806. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5807. var n = znear;
  5808. var f = zfar;
  5809. var t = 1.0 / (Math.tan(fov * 0.5));
  5810. var a = isVerticalFovFixed ? (t / aspect) : t;
  5811. var b = isVerticalFovFixed ? t : (t * aspect);
  5812. var c = (f + n) / (f - n);
  5813. var d = -2.0 * f * n / (f - n);
  5814. 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);
  5815. };
  5816. /**
  5817. * Returns a new Matrix as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5818. */
  5819. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  5820. var matrix = Matrix.Zero();
  5821. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  5822. return matrix;
  5823. };
  5824. /**
  5825. * Sets the passed matrix "result" as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5826. */
  5827. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  5828. //alternatively this could be expressed as:
  5829. // m = PerspectiveFovLHToRef
  5830. // m[10] *= -1.0;
  5831. // m[11] *= -1.0;
  5832. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  5833. var n = znear;
  5834. var f = zfar;
  5835. var t = 1.0 / (Math.tan(fov * 0.5));
  5836. var a = isVerticalFovFixed ? (t / aspect) : t;
  5837. var b = isVerticalFovFixed ? t : (t * aspect);
  5838. var c = -(f + n) / (f - n);
  5839. var d = -2 * f * n / (f - n);
  5840. 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);
  5841. };
  5842. /**
  5843. * Sets the passed matrix "result" as a left-handed perspective projection matrix for WebVR computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  5844. */
  5845. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  5846. if (rightHanded === void 0) { rightHanded = false; }
  5847. var rightHandedFactor = rightHanded ? -1 : 1;
  5848. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  5849. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  5850. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  5851. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  5852. var xScale = 2.0 / (leftTan + rightTan);
  5853. var yScale = 2.0 / (upTan + downTan);
  5854. result.m[0] = xScale;
  5855. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  5856. result.m[5] = yScale;
  5857. result.m[6] = result.m[7] = 0.0;
  5858. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  5859. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  5860. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  5861. result.m[10] = -zfar / (znear - zfar);
  5862. result.m[11] = 1.0 * rightHandedFactor;
  5863. result.m[12] = result.m[13] = result.m[15] = 0.0;
  5864. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  5865. // result.m[14] = (znear * zfar) / (znear - zfar);
  5866. result._markAsUpdated();
  5867. };
  5868. /**
  5869. * Returns the final transformation matrix : world * view * projection * viewport
  5870. */
  5871. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  5872. var cw = viewport.width;
  5873. var ch = viewport.height;
  5874. var cx = viewport.x;
  5875. var cy = viewport.y;
  5876. 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);
  5877. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  5878. };
  5879. /**
  5880. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  5881. */
  5882. Matrix.GetAsMatrix2x2 = function (matrix) {
  5883. return new Float32Array([
  5884. matrix.m[0], matrix.m[1],
  5885. matrix.m[4], matrix.m[5]
  5886. ]);
  5887. };
  5888. /**
  5889. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  5890. */
  5891. Matrix.GetAsMatrix3x3 = function (matrix) {
  5892. return new Float32Array([
  5893. matrix.m[0], matrix.m[1], matrix.m[2],
  5894. matrix.m[4], matrix.m[5], matrix.m[6],
  5895. matrix.m[8], matrix.m[9], matrix.m[10]
  5896. ]);
  5897. };
  5898. /**
  5899. * Compute the transpose of the passed Matrix.
  5900. * Returns a new Matrix.
  5901. */
  5902. Matrix.Transpose = function (matrix) {
  5903. var result = new Matrix();
  5904. Matrix.TransposeToRef(matrix, result);
  5905. return result;
  5906. };
  5907. /**
  5908. * Compute the transpose of the passed Matrix and store it in the result matrix.
  5909. */
  5910. Matrix.TransposeToRef = function (matrix, result) {
  5911. result.m[0] = matrix.m[0];
  5912. result.m[1] = matrix.m[4];
  5913. result.m[2] = matrix.m[8];
  5914. result.m[3] = matrix.m[12];
  5915. result.m[4] = matrix.m[1];
  5916. result.m[5] = matrix.m[5];
  5917. result.m[6] = matrix.m[9];
  5918. result.m[7] = matrix.m[13];
  5919. result.m[8] = matrix.m[2];
  5920. result.m[9] = matrix.m[6];
  5921. result.m[10] = matrix.m[10];
  5922. result.m[11] = matrix.m[14];
  5923. result.m[12] = matrix.m[3];
  5924. result.m[13] = matrix.m[7];
  5925. result.m[14] = matrix.m[11];
  5926. result.m[15] = matrix.m[15];
  5927. };
  5928. /**
  5929. * Returns a new Matrix as the reflection matrix across the passed plane.
  5930. */
  5931. Matrix.Reflection = function (plane) {
  5932. var matrix = new Matrix();
  5933. Matrix.ReflectionToRef(plane, matrix);
  5934. return matrix;
  5935. };
  5936. /**
  5937. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  5938. */
  5939. Matrix.ReflectionToRef = function (plane, result) {
  5940. plane.normalize();
  5941. var x = plane.normal.x;
  5942. var y = plane.normal.y;
  5943. var z = plane.normal.z;
  5944. var temp = -2 * x;
  5945. var temp2 = -2 * y;
  5946. var temp3 = -2 * z;
  5947. result.m[0] = (temp * x) + 1;
  5948. result.m[1] = temp2 * x;
  5949. result.m[2] = temp3 * x;
  5950. result.m[3] = 0.0;
  5951. result.m[4] = temp * y;
  5952. result.m[5] = (temp2 * y) + 1;
  5953. result.m[6] = temp3 * y;
  5954. result.m[7] = 0.0;
  5955. result.m[8] = temp * z;
  5956. result.m[9] = temp2 * z;
  5957. result.m[10] = (temp3 * z) + 1;
  5958. result.m[11] = 0.0;
  5959. result.m[12] = temp * plane.d;
  5960. result.m[13] = temp2 * plane.d;
  5961. result.m[14] = temp3 * plane.d;
  5962. result.m[15] = 1.0;
  5963. result._markAsUpdated();
  5964. };
  5965. /**
  5966. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  5967. */
  5968. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  5969. result.m[0] = xaxis.x;
  5970. result.m[1] = xaxis.y;
  5971. result.m[2] = xaxis.z;
  5972. result.m[3] = 0.0;
  5973. result.m[4] = yaxis.x;
  5974. result.m[5] = yaxis.y;
  5975. result.m[6] = yaxis.z;
  5976. result.m[7] = 0.0;
  5977. result.m[8] = zaxis.x;
  5978. result.m[9] = zaxis.y;
  5979. result.m[10] = zaxis.z;
  5980. result.m[11] = 0.0;
  5981. result.m[12] = 0.0;
  5982. result.m[13] = 0.0;
  5983. result.m[14] = 0.0;
  5984. result.m[15] = 1.0;
  5985. result._markAsUpdated();
  5986. };
  5987. /**
  5988. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  5989. */
  5990. Matrix.FromQuaternionToRef = function (quat, result) {
  5991. var xx = quat.x * quat.x;
  5992. var yy = quat.y * quat.y;
  5993. var zz = quat.z * quat.z;
  5994. var xy = quat.x * quat.y;
  5995. var zw = quat.z * quat.w;
  5996. var zx = quat.z * quat.x;
  5997. var yw = quat.y * quat.w;
  5998. var yz = quat.y * quat.z;
  5999. var xw = quat.x * quat.w;
  6000. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6001. result.m[1] = 2.0 * (xy + zw);
  6002. result.m[2] = 2.0 * (zx - yw);
  6003. result.m[3] = 0.0;
  6004. result.m[4] = 2.0 * (xy - zw);
  6005. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6006. result.m[6] = 2.0 * (yz + xw);
  6007. result.m[7] = 0.0;
  6008. result.m[8] = 2.0 * (zx + yw);
  6009. result.m[9] = 2.0 * (yz - xw);
  6010. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6011. result.m[11] = 0.0;
  6012. result.m[12] = 0.0;
  6013. result.m[13] = 0.0;
  6014. result.m[14] = 0.0;
  6015. result.m[15] = 1.0;
  6016. result._markAsUpdated();
  6017. };
  6018. Matrix._tempQuaternion = new Quaternion();
  6019. Matrix._xAxis = Vector3.Zero();
  6020. Matrix._yAxis = Vector3.Zero();
  6021. Matrix._zAxis = Vector3.Zero();
  6022. Matrix._updateFlagSeed = 0;
  6023. Matrix._identityReadOnly = Matrix.Identity();
  6024. return Matrix;
  6025. }());
  6026. BABYLON.Matrix = Matrix;
  6027. var Plane = /** @class */ (function () {
  6028. /**
  6029. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6030. */
  6031. function Plane(a, b, c, d) {
  6032. this.normal = new Vector3(a, b, c);
  6033. this.d = d;
  6034. }
  6035. /**
  6036. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6037. */
  6038. Plane.prototype.asArray = function () {
  6039. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6040. };
  6041. // Methods
  6042. /**
  6043. * Returns a new plane copied from the current Plane.
  6044. */
  6045. Plane.prototype.clone = function () {
  6046. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6047. };
  6048. /**
  6049. * Returns the string "Plane".
  6050. */
  6051. Plane.prototype.getClassName = function () {
  6052. return "Plane";
  6053. };
  6054. /**
  6055. * Returns the Plane hash code.
  6056. */
  6057. Plane.prototype.getHashCode = function () {
  6058. var hash = this.normal.getHashCode();
  6059. hash = (hash * 397) ^ (this.d || 0);
  6060. return hash;
  6061. };
  6062. /**
  6063. * Normalize the current Plane in place.
  6064. * Returns the updated Plane.
  6065. */
  6066. Plane.prototype.normalize = function () {
  6067. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6068. var magnitude = 0.0;
  6069. if (norm !== 0) {
  6070. magnitude = 1.0 / norm;
  6071. }
  6072. this.normal.x *= magnitude;
  6073. this.normal.y *= magnitude;
  6074. this.normal.z *= magnitude;
  6075. this.d *= magnitude;
  6076. return this;
  6077. };
  6078. /**
  6079. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  6080. */
  6081. Plane.prototype.transform = function (transformation) {
  6082. var transposedMatrix = Matrix.Transpose(transformation);
  6083. var x = this.normal.x;
  6084. var y = this.normal.y;
  6085. var z = this.normal.z;
  6086. var d = this.d;
  6087. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6088. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6089. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6090. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6091. return new Plane(normalX, normalY, normalZ, finalD);
  6092. };
  6093. /**
  6094. * Returns the dot product (float) of the point coordinates and the plane normal.
  6095. */
  6096. Plane.prototype.dotCoordinate = function (point) {
  6097. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6098. };
  6099. /**
  6100. * Updates the current Plane from the plane defined by the three passed points.
  6101. * Returns the updated Plane.
  6102. */
  6103. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6104. var x1 = point2.x - point1.x;
  6105. var y1 = point2.y - point1.y;
  6106. var z1 = point2.z - point1.z;
  6107. var x2 = point3.x - point1.x;
  6108. var y2 = point3.y - point1.y;
  6109. var z2 = point3.z - point1.z;
  6110. var yz = (y1 * z2) - (z1 * y2);
  6111. var xz = (z1 * x2) - (x1 * z2);
  6112. var xy = (x1 * y2) - (y1 * x2);
  6113. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6114. var invPyth;
  6115. if (pyth !== 0) {
  6116. invPyth = 1.0 / pyth;
  6117. }
  6118. else {
  6119. invPyth = 0.0;
  6120. }
  6121. this.normal.x = yz * invPyth;
  6122. this.normal.y = xz * invPyth;
  6123. this.normal.z = xy * invPyth;
  6124. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6125. return this;
  6126. };
  6127. /**
  6128. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6129. */
  6130. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6131. var dot = Vector3.Dot(this.normal, direction);
  6132. return (dot <= epsilon);
  6133. };
  6134. /**
  6135. * Returns the signed distance (float) from the passed point to the Plane.
  6136. */
  6137. Plane.prototype.signedDistanceTo = function (point) {
  6138. return Vector3.Dot(point, this.normal) + this.d;
  6139. };
  6140. // Statics
  6141. /**
  6142. * Returns a new Plane from the passed array.
  6143. */
  6144. Plane.FromArray = function (array) {
  6145. return new Plane(array[0], array[1], array[2], array[3]);
  6146. };
  6147. /**
  6148. * Returns a new Plane defined by the three passed points.
  6149. */
  6150. Plane.FromPoints = function (point1, point2, point3) {
  6151. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6152. result.copyFromPoints(point1, point2, point3);
  6153. return result;
  6154. };
  6155. /**
  6156. * Returns a new Plane the normal vector to this plane at the passed origin point.
  6157. * Note : the vector "normal" is updated because normalized.
  6158. */
  6159. Plane.FromPositionAndNormal = function (origin, normal) {
  6160. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6161. normal.normalize();
  6162. result.normal = normal;
  6163. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6164. return result;
  6165. };
  6166. /**
  6167. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  6168. */
  6169. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6170. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6171. return Vector3.Dot(point, normal) + d;
  6172. };
  6173. return Plane;
  6174. }());
  6175. BABYLON.Plane = Plane;
  6176. var Viewport = /** @class */ (function () {
  6177. /**
  6178. * Creates a Viewport object located at (x, y) and sized (width, height).
  6179. */
  6180. function Viewport(x, y, width, height) {
  6181. this.x = x;
  6182. this.y = y;
  6183. this.width = width;
  6184. this.height = height;
  6185. }
  6186. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6187. if (renderWidthOrEngine.getRenderWidth) {
  6188. var engine = renderWidthOrEngine;
  6189. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6190. }
  6191. var renderWidth = renderWidthOrEngine;
  6192. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6193. };
  6194. /**
  6195. * Returns a new Viewport copied from the current one.
  6196. */
  6197. Viewport.prototype.clone = function () {
  6198. return new Viewport(this.x, this.y, this.width, this.height);
  6199. };
  6200. return Viewport;
  6201. }());
  6202. BABYLON.Viewport = Viewport;
  6203. var Frustum = /** @class */ (function () {
  6204. function Frustum() {
  6205. }
  6206. /**
  6207. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  6208. */
  6209. Frustum.GetPlanes = function (transform) {
  6210. var frustumPlanes = [];
  6211. for (var index = 0; index < 6; index++) {
  6212. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6213. }
  6214. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6215. return frustumPlanes;
  6216. };
  6217. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6218. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6219. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6220. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6221. frustumPlane.d = transform.m[15] + transform.m[14];
  6222. frustumPlane.normalize();
  6223. };
  6224. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6225. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6226. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6227. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6228. frustumPlane.d = transform.m[15] - transform.m[14];
  6229. frustumPlane.normalize();
  6230. };
  6231. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6232. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6233. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6234. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6235. frustumPlane.d = transform.m[15] + transform.m[12];
  6236. frustumPlane.normalize();
  6237. };
  6238. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6239. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6240. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6241. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6242. frustumPlane.d = transform.m[15] - transform.m[12];
  6243. frustumPlane.normalize();
  6244. };
  6245. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6246. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6247. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6248. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6249. frustumPlane.d = transform.m[15] - transform.m[13];
  6250. frustumPlane.normalize();
  6251. };
  6252. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6253. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6254. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6255. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6256. frustumPlane.d = transform.m[15] + transform.m[13];
  6257. frustumPlane.normalize();
  6258. };
  6259. /**
  6260. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  6261. */
  6262. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6263. // Near
  6264. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6265. // Far
  6266. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6267. // Left
  6268. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6269. // Right
  6270. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6271. // Top
  6272. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6273. // Bottom
  6274. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6275. };
  6276. return Frustum;
  6277. }());
  6278. BABYLON.Frustum = Frustum;
  6279. var Space;
  6280. (function (Space) {
  6281. Space[Space["LOCAL"] = 0] = "LOCAL";
  6282. Space[Space["WORLD"] = 1] = "WORLD";
  6283. Space[Space["BONE"] = 2] = "BONE";
  6284. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6285. var Axis = /** @class */ (function () {
  6286. function Axis() {
  6287. }
  6288. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6289. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6290. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6291. return Axis;
  6292. }());
  6293. BABYLON.Axis = Axis;
  6294. ;
  6295. var BezierCurve = /** @class */ (function () {
  6296. function BezierCurve() {
  6297. }
  6298. /**
  6299. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  6300. */
  6301. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6302. // Extract X (which is equal to time here)
  6303. var f0 = 1 - 3 * x2 + 3 * x1;
  6304. var f1 = 3 * x2 - 6 * x1;
  6305. var f2 = 3 * x1;
  6306. var refinedT = t;
  6307. for (var i = 0; i < 5; i++) {
  6308. var refinedT2 = refinedT * refinedT;
  6309. var refinedT3 = refinedT2 * refinedT;
  6310. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6311. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6312. refinedT -= (x - t) * slope;
  6313. refinedT = Math.min(1, Math.max(0, refinedT));
  6314. }
  6315. // Resolve cubic bezier for the given x
  6316. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6317. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6318. Math.pow(refinedT, 3);
  6319. };
  6320. return BezierCurve;
  6321. }());
  6322. BABYLON.BezierCurve = BezierCurve;
  6323. var Orientation;
  6324. (function (Orientation) {
  6325. Orientation[Orientation["CW"] = 0] = "CW";
  6326. Orientation[Orientation["CCW"] = 1] = "CCW";
  6327. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6328. var Angle = /** @class */ (function () {
  6329. /**
  6330. * Creates an Angle object of "radians" radians (float).
  6331. */
  6332. function Angle(radians) {
  6333. var _this = this;
  6334. /**
  6335. * Returns the Angle value in degrees (float).
  6336. */
  6337. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  6338. /**
  6339. * Returns the Angle value in radians (float).
  6340. */
  6341. this.radians = function () { return _this._radians; };
  6342. this._radians = radians;
  6343. if (this._radians < 0.0)
  6344. this._radians += (2.0 * Math.PI);
  6345. }
  6346. /**
  6347. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  6348. */
  6349. Angle.BetweenTwoPoints = function (a, b) {
  6350. var delta = b.subtract(a);
  6351. var theta = Math.atan2(delta.y, delta.x);
  6352. return new Angle(theta);
  6353. };
  6354. /**
  6355. * Returns a new Angle object from the passed float in radians.
  6356. */
  6357. Angle.FromRadians = function (radians) {
  6358. return new Angle(radians);
  6359. };
  6360. /**
  6361. * Returns a new Angle object from the passed float in degrees.
  6362. */
  6363. Angle.FromDegrees = function (degrees) {
  6364. return new Angle(degrees * Math.PI / 180.0);
  6365. };
  6366. return Angle;
  6367. }());
  6368. BABYLON.Angle = Angle;
  6369. var Arc2 = /** @class */ (function () {
  6370. /**
  6371. * Creates an Arc object from the three passed points : start, middle and end.
  6372. */
  6373. function Arc2(startPoint, midPoint, endPoint) {
  6374. this.startPoint = startPoint;
  6375. this.midPoint = midPoint;
  6376. this.endPoint = endPoint;
  6377. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6378. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6379. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6380. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6381. 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);
  6382. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6383. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6384. var a1 = this.startAngle.degrees();
  6385. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6386. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6387. // angles correction
  6388. if (a2 - a1 > +180.0)
  6389. a2 -= 360.0;
  6390. if (a2 - a1 < -180.0)
  6391. a2 += 360.0;
  6392. if (a3 - a2 > +180.0)
  6393. a3 -= 360.0;
  6394. if (a3 - a2 < -180.0)
  6395. a3 += 360.0;
  6396. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6397. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6398. }
  6399. return Arc2;
  6400. }());
  6401. BABYLON.Arc2 = Arc2;
  6402. var Path2 = /** @class */ (function () {
  6403. /**
  6404. * Creates a Path2 object from the starting 2D coordinates x and y.
  6405. */
  6406. function Path2(x, y) {
  6407. this._points = new Array();
  6408. this._length = 0.0;
  6409. this.closed = false;
  6410. this._points.push(new Vector2(x, y));
  6411. }
  6412. /**
  6413. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  6414. * Returns the updated Path2.
  6415. */
  6416. Path2.prototype.addLineTo = function (x, y) {
  6417. if (this.closed) {
  6418. return this;
  6419. }
  6420. var newPoint = new Vector2(x, y);
  6421. var previousPoint = this._points[this._points.length - 1];
  6422. this._points.push(newPoint);
  6423. this._length += newPoint.subtract(previousPoint).length();
  6424. return this;
  6425. };
  6426. /**
  6427. * 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.
  6428. * Returns the updated Path2.
  6429. */
  6430. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6431. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6432. if (this.closed) {
  6433. return this;
  6434. }
  6435. var startPoint = this._points[this._points.length - 1];
  6436. var midPoint = new Vector2(midX, midY);
  6437. var endPoint = new Vector2(endX, endY);
  6438. var arc = new Arc2(startPoint, midPoint, endPoint);
  6439. var increment = arc.angle.radians() / numberOfSegments;
  6440. if (arc.orientation === Orientation.CW)
  6441. increment *= -1;
  6442. var currentAngle = arc.startAngle.radians() + increment;
  6443. for (var i = 0; i < numberOfSegments; i++) {
  6444. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6445. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6446. this.addLineTo(x, y);
  6447. currentAngle += increment;
  6448. }
  6449. return this;
  6450. };
  6451. /**
  6452. * Closes the Path2.
  6453. * Returns the Path2.
  6454. */
  6455. Path2.prototype.close = function () {
  6456. this.closed = true;
  6457. return this;
  6458. };
  6459. /**
  6460. * Returns the Path2 total length (float).
  6461. */
  6462. Path2.prototype.length = function () {
  6463. var result = this._length;
  6464. if (!this.closed) {
  6465. var lastPoint = this._points[this._points.length - 1];
  6466. var firstPoint = this._points[0];
  6467. result += (firstPoint.subtract(lastPoint).length());
  6468. }
  6469. return result;
  6470. };
  6471. /**
  6472. * Returns the Path2 internal array of points.
  6473. */
  6474. Path2.prototype.getPoints = function () {
  6475. return this._points;
  6476. };
  6477. /**
  6478. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6479. */
  6480. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  6481. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  6482. return Vector2.Zero();
  6483. }
  6484. var lengthPosition = normalizedLengthPosition * this.length();
  6485. var previousOffset = 0;
  6486. for (var i = 0; i < this._points.length; i++) {
  6487. var j = (i + 1) % this._points.length;
  6488. var a = this._points[i];
  6489. var b = this._points[j];
  6490. var bToA = b.subtract(a);
  6491. var nextOffset = (bToA.length() + previousOffset);
  6492. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  6493. var dir = bToA.normalize();
  6494. var localOffset = lengthPosition - previousOffset;
  6495. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  6496. }
  6497. previousOffset = nextOffset;
  6498. }
  6499. return Vector2.Zero();
  6500. };
  6501. /**
  6502. * Returns a new Path2 starting at the coordinates (x, y).
  6503. */
  6504. Path2.StartingAt = function (x, y) {
  6505. return new Path2(x, y);
  6506. };
  6507. return Path2;
  6508. }());
  6509. BABYLON.Path2 = Path2;
  6510. var Path3D = /** @class */ (function () {
  6511. /**
  6512. * new Path3D(path, normal, raw)
  6513. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  6514. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  6515. * path : an array of Vector3, the curve axis of the Path3D
  6516. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  6517. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  6518. */
  6519. function Path3D(path, firstNormal, raw) {
  6520. if (firstNormal === void 0) { firstNormal = null; }
  6521. this.path = path;
  6522. this._curve = new Array();
  6523. this._distances = new Array();
  6524. this._tangents = new Array();
  6525. this._normals = new Array();
  6526. this._binormals = new Array();
  6527. for (var p = 0; p < path.length; p++) {
  6528. this._curve[p] = path[p].clone(); // hard copy
  6529. }
  6530. this._raw = raw || false;
  6531. this._compute(firstNormal);
  6532. }
  6533. /**
  6534. * Returns the Path3D array of successive Vector3 designing its curve.
  6535. */
  6536. Path3D.prototype.getCurve = function () {
  6537. return this._curve;
  6538. };
  6539. /**
  6540. * Returns an array populated with tangent vectors on each Path3D curve point.
  6541. */
  6542. Path3D.prototype.getTangents = function () {
  6543. return this._tangents;
  6544. };
  6545. /**
  6546. * Returns an array populated with normal vectors on each Path3D curve point.
  6547. */
  6548. Path3D.prototype.getNormals = function () {
  6549. return this._normals;
  6550. };
  6551. /**
  6552. * Returns an array populated with binormal vectors on each Path3D curve point.
  6553. */
  6554. Path3D.prototype.getBinormals = function () {
  6555. return this._binormals;
  6556. };
  6557. /**
  6558. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  6559. */
  6560. Path3D.prototype.getDistances = function () {
  6561. return this._distances;
  6562. };
  6563. /**
  6564. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  6565. * Returns the same object updated.
  6566. */
  6567. Path3D.prototype.update = function (path, firstNormal) {
  6568. if (firstNormal === void 0) { firstNormal = null; }
  6569. for (var p = 0; p < path.length; p++) {
  6570. this._curve[p].x = path[p].x;
  6571. this._curve[p].y = path[p].y;
  6572. this._curve[p].z = path[p].z;
  6573. }
  6574. this._compute(firstNormal);
  6575. return this;
  6576. };
  6577. // private function compute() : computes tangents, normals and binormals
  6578. Path3D.prototype._compute = function (firstNormal) {
  6579. var l = this._curve.length;
  6580. // first and last tangents
  6581. this._tangents[0] = this._getFirstNonNullVector(0);
  6582. if (!this._raw) {
  6583. this._tangents[0].normalize();
  6584. }
  6585. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  6586. if (!this._raw) {
  6587. this._tangents[l - 1].normalize();
  6588. }
  6589. // normals and binormals at first point : arbitrary vector with _normalVector()
  6590. var tg0 = this._tangents[0];
  6591. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  6592. this._normals[0] = pp0;
  6593. if (!this._raw) {
  6594. this._normals[0].normalize();
  6595. }
  6596. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  6597. if (!this._raw) {
  6598. this._binormals[0].normalize();
  6599. }
  6600. this._distances[0] = 0.0;
  6601. // normals and binormals : next points
  6602. var prev; // previous vector (segment)
  6603. var cur; // current vector (segment)
  6604. var curTang; // current tangent
  6605. // previous normal
  6606. var prevBinor; // previous binormal
  6607. for (var i = 1; i < l; i++) {
  6608. // tangents
  6609. prev = this._getLastNonNullVector(i);
  6610. if (i < l - 1) {
  6611. cur = this._getFirstNonNullVector(i);
  6612. this._tangents[i] = prev.add(cur);
  6613. this._tangents[i].normalize();
  6614. }
  6615. this._distances[i] = this._distances[i - 1] + prev.length();
  6616. // normals and binormals
  6617. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  6618. curTang = this._tangents[i];
  6619. prevBinor = this._binormals[i - 1];
  6620. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  6621. if (!this._raw) {
  6622. this._normals[i].normalize();
  6623. }
  6624. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  6625. if (!this._raw) {
  6626. this._binormals[i].normalize();
  6627. }
  6628. }
  6629. };
  6630. // private function getFirstNonNullVector(index)
  6631. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  6632. Path3D.prototype._getFirstNonNullVector = function (index) {
  6633. var i = 1;
  6634. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  6635. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  6636. i++;
  6637. nNVector = this._curve[index + i].subtract(this._curve[index]);
  6638. }
  6639. return nNVector;
  6640. };
  6641. // private function getLastNonNullVector(index)
  6642. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  6643. Path3D.prototype._getLastNonNullVector = function (index) {
  6644. var i = 1;
  6645. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  6646. while (nLVector.length() === 0 && index > i + 1) {
  6647. i++;
  6648. nLVector = this._curve[index].subtract(this._curve[index - i]);
  6649. }
  6650. return nLVector;
  6651. };
  6652. // private function normalVector(v0, vt, va) :
  6653. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  6654. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  6655. Path3D.prototype._normalVector = function (v0, vt, va) {
  6656. var normal0;
  6657. var tgl = vt.length();
  6658. if (tgl === 0.0) {
  6659. tgl = 1.0;
  6660. }
  6661. if (va === undefined || va === null) {
  6662. var point;
  6663. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  6664. point = new Vector3(0.0, -1.0, 0.0);
  6665. }
  6666. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  6667. point = new Vector3(1.0, 0.0, 0.0);
  6668. }
  6669. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  6670. point = new Vector3(0.0, 0.0, 1.0);
  6671. }
  6672. else {
  6673. point = Vector3.Zero();
  6674. }
  6675. normal0 = Vector3.Cross(vt, point);
  6676. }
  6677. else {
  6678. normal0 = Vector3.Cross(vt, va);
  6679. Vector3.CrossToRef(normal0, vt, normal0);
  6680. }
  6681. normal0.normalize();
  6682. return normal0;
  6683. };
  6684. return Path3D;
  6685. }());
  6686. BABYLON.Path3D = Path3D;
  6687. var Curve3 = /** @class */ (function () {
  6688. /**
  6689. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  6690. * A Curve3 is designed from a series of successive Vector3.
  6691. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  6692. */
  6693. function Curve3(points) {
  6694. this._length = 0.0;
  6695. this._points = points;
  6696. this._length = this._computeLength(points);
  6697. }
  6698. /**
  6699. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  6700. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  6701. * @param v1 (Vector3) the control point
  6702. * @param v2 (Vector3) the end point of the Quadratic Bezier
  6703. * @param nbPoints (integer) the wanted number of points in the curve
  6704. */
  6705. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  6706. nbPoints = nbPoints > 2 ? nbPoints : 3;
  6707. var bez = new Array();
  6708. var equation = function (t, val0, val1, val2) {
  6709. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  6710. return res;
  6711. };
  6712. for (var i = 0; i <= nbPoints; i++) {
  6713. 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)));
  6714. }
  6715. return new Curve3(bez);
  6716. };
  6717. /**
  6718. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  6719. * @param v0 (Vector3) the origin point of the Cubic Bezier
  6720. * @param v1 (Vector3) the first control point
  6721. * @param v2 (Vector3) the second control point
  6722. * @param v3 (Vector3) the end point of the Cubic Bezier
  6723. * @param nbPoints (integer) the wanted number of points in the curve
  6724. */
  6725. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  6726. nbPoints = nbPoints > 3 ? nbPoints : 4;
  6727. var bez = new Array();
  6728. var equation = function (t, val0, val1, val2, val3) {
  6729. 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;
  6730. return res;
  6731. };
  6732. for (var i = 0; i <= nbPoints; i++) {
  6733. 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)));
  6734. }
  6735. return new Curve3(bez);
  6736. };
  6737. /**
  6738. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  6739. * @param p1 (Vector3) the origin point of the Hermite Spline
  6740. * @param t1 (Vector3) the tangent vector at the origin point
  6741. * @param p2 (Vector3) the end point of the Hermite Spline
  6742. * @param t2 (Vector3) the tangent vector at the end point
  6743. * @param nbPoints (integer) the wanted number of points in the curve
  6744. */
  6745. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  6746. var hermite = new Array();
  6747. var step = 1.0 / nbPoints;
  6748. for (var i = 0; i <= nbPoints; i++) {
  6749. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  6750. }
  6751. return new Curve3(hermite);
  6752. };
  6753. /**
  6754. * Returns a Curve3 object along a CatmullRom Spline curve :
  6755. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  6756. * @param nbPoints (integer) the wanted number of points between each curve control points.
  6757. */
  6758. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  6759. var totalPoints = new Array();
  6760. totalPoints.push(points[0].clone());
  6761. Array.prototype.push.apply(totalPoints, points);
  6762. totalPoints.push(points[points.length - 1].clone());
  6763. var catmullRom = new Array();
  6764. var step = 1.0 / nbPoints;
  6765. var amount = 0.0;
  6766. for (var i = 0; i < totalPoints.length - 3; i++) {
  6767. amount = 0;
  6768. for (var c = 0; c < nbPoints; c++) {
  6769. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6770. amount += step;
  6771. }
  6772. }
  6773. i--;
  6774. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  6775. return new Curve3(catmullRom);
  6776. };
  6777. /**
  6778. * Returns the Curve3 stored array of successive Vector3
  6779. */
  6780. Curve3.prototype.getPoints = function () {
  6781. return this._points;
  6782. };
  6783. /**
  6784. * Returns the computed length (float) of the curve.
  6785. */
  6786. Curve3.prototype.length = function () {
  6787. return this._length;
  6788. };
  6789. /**
  6790. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  6791. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  6792. * curveA and curveB keep unchanged.
  6793. */
  6794. Curve3.prototype.continue = function (curve) {
  6795. var lastPoint = this._points[this._points.length - 1];
  6796. var continuedPoints = this._points.slice();
  6797. var curvePoints = curve.getPoints();
  6798. for (var i = 1; i < curvePoints.length; i++) {
  6799. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  6800. }
  6801. var continuedCurve = new Curve3(continuedPoints);
  6802. return continuedCurve;
  6803. };
  6804. Curve3.prototype._computeLength = function (path) {
  6805. var l = 0;
  6806. for (var i = 1; i < path.length; i++) {
  6807. l += (path[i].subtract(path[i - 1])).length();
  6808. }
  6809. return l;
  6810. };
  6811. return Curve3;
  6812. }());
  6813. BABYLON.Curve3 = Curve3;
  6814. // Vertex formats
  6815. var PositionNormalVertex = /** @class */ (function () {
  6816. function PositionNormalVertex(position, normal) {
  6817. if (position === void 0) { position = Vector3.Zero(); }
  6818. if (normal === void 0) { normal = Vector3.Up(); }
  6819. this.position = position;
  6820. this.normal = normal;
  6821. }
  6822. PositionNormalVertex.prototype.clone = function () {
  6823. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  6824. };
  6825. return PositionNormalVertex;
  6826. }());
  6827. BABYLON.PositionNormalVertex = PositionNormalVertex;
  6828. var PositionNormalTextureVertex = /** @class */ (function () {
  6829. function PositionNormalTextureVertex(position, normal, uv) {
  6830. if (position === void 0) { position = Vector3.Zero(); }
  6831. if (normal === void 0) { normal = Vector3.Up(); }
  6832. if (uv === void 0) { uv = Vector2.Zero(); }
  6833. this.position = position;
  6834. this.normal = normal;
  6835. this.uv = uv;
  6836. }
  6837. PositionNormalTextureVertex.prototype.clone = function () {
  6838. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  6839. };
  6840. return PositionNormalTextureVertex;
  6841. }());
  6842. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  6843. // Temporary pre-allocated objects for engine internal use
  6844. // usage in any internal function :
  6845. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  6846. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  6847. var Tmp = /** @class */ (function () {
  6848. function Tmp() {
  6849. }
  6850. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  6851. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  6852. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  6853. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  6854. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  6855. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  6856. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  6857. Matrix.Zero(), Matrix.Zero(),
  6858. Matrix.Zero(), Matrix.Zero(),
  6859. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  6860. return Tmp;
  6861. }());
  6862. BABYLON.Tmp = Tmp;
  6863. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  6864. var MathTmp = /** @class */ (function () {
  6865. function MathTmp() {
  6866. }
  6867. MathTmp.Vector3 = [Vector3.Zero()];
  6868. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  6869. MathTmp.Quaternion = [Quaternion.Zero()];
  6870. return MathTmp;
  6871. }());
  6872. })(BABYLON || (BABYLON = {}));
  6873. //# sourceMappingURL=babylon.math.js.map
  6874. "use strict";
  6875. var BABYLON;
  6876. (function (BABYLON) {
  6877. var Scalar = /** @class */ (function () {
  6878. function Scalar() {
  6879. }
  6880. /**
  6881. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  6882. */
  6883. Scalar.WithinEpsilon = function (a, b, epsilon) {
  6884. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  6885. var num = a - b;
  6886. return -epsilon <= num && num <= epsilon;
  6887. };
  6888. /**
  6889. * Returns a string : the upper case translation of the number i to hexadecimal.
  6890. */
  6891. Scalar.ToHex = function (i) {
  6892. var str = i.toString(16);
  6893. if (i <= 15) {
  6894. return ("0" + str).toUpperCase();
  6895. }
  6896. return str.toUpperCase();
  6897. };
  6898. /**
  6899. * Returns -1 if value is negative and +1 is value is positive.
  6900. * Returns the value itself if it's equal to zero.
  6901. */
  6902. Scalar.Sign = function (value) {
  6903. value = +value; // convert to a number
  6904. if (value === 0 || isNaN(value))
  6905. return value;
  6906. return value > 0 ? 1 : -1;
  6907. };
  6908. /**
  6909. * Returns the value itself if it's between min and max.
  6910. * Returns min if the value is lower than min.
  6911. * Returns max if the value is greater than max.
  6912. */
  6913. Scalar.Clamp = function (value, min, max) {
  6914. if (min === void 0) { min = 0; }
  6915. if (max === void 0) { max = 1; }
  6916. return Math.min(max, Math.max(min, value));
  6917. };
  6918. /**
  6919. * Returns the log2 of value.
  6920. */
  6921. Scalar.Log2 = function (value) {
  6922. return Math.log(value) * Math.LOG2E;
  6923. };
  6924. /**
  6925. * Loops the value, so that it is never larger than length and never smaller than 0.
  6926. *
  6927. * This is similar to the modulo operator but it works with floating point numbers.
  6928. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  6929. * With t = 5 and length = 2.5, the result would be 0.0.
  6930. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  6931. */
  6932. Scalar.Repeat = function (value, length) {
  6933. return value - Math.floor(value / length) * length;
  6934. };
  6935. /**
  6936. * Normalize the value between 0.0 and 1.0 using min and max values
  6937. */
  6938. Scalar.Normalize = function (value, min, max) {
  6939. return (value - min) / (max - min);
  6940. };
  6941. /**
  6942. * Denormalize the value from 0.0 and 1.0 using min and max values
  6943. */
  6944. Scalar.Denormalize = function (normalized, min, max) {
  6945. return (normalized * (max - min) + min);
  6946. };
  6947. /**
  6948. * Calculates the shortest difference between two given angles given in degrees.
  6949. */
  6950. Scalar.DeltaAngle = function (current, target) {
  6951. var num = Scalar.Repeat(target - current, 360.0);
  6952. if (num > 180.0) {
  6953. num -= 360.0;
  6954. }
  6955. return num;
  6956. };
  6957. /**
  6958. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  6959. *
  6960. * The returned value will move back and forth between 0 and length
  6961. */
  6962. Scalar.PingPong = function (tx, length) {
  6963. var t = Scalar.Repeat(tx, length * 2.0);
  6964. return length - Math.abs(t - length);
  6965. };
  6966. /**
  6967. * Interpolates between min and max with smoothing at the limits.
  6968. *
  6969. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  6970. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  6971. */
  6972. Scalar.SmoothStep = function (from, to, tx) {
  6973. var t = Scalar.Clamp(tx);
  6974. t = -2.0 * t * t * t + 3.0 * t * t;
  6975. return to * t + from * (1.0 - t);
  6976. };
  6977. /**
  6978. * Moves a value current towards target.
  6979. *
  6980. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  6981. * Negative values of maxDelta pushes the value away from target.
  6982. */
  6983. Scalar.MoveTowards = function (current, target, maxDelta) {
  6984. var result = 0;
  6985. if (Math.abs(target - current) <= maxDelta) {
  6986. result = target;
  6987. }
  6988. else {
  6989. result = current + Scalar.Sign(target - current) * maxDelta;
  6990. }
  6991. return result;
  6992. };
  6993. /**
  6994. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  6995. *
  6996. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  6997. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  6998. */
  6999. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7000. var num = Scalar.DeltaAngle(current, target);
  7001. var result = 0;
  7002. if (-maxDelta < num && num < maxDelta) {
  7003. result = target;
  7004. }
  7005. else {
  7006. target = current + num;
  7007. result = Scalar.MoveTowards(current, target, maxDelta);
  7008. }
  7009. return result;
  7010. };
  7011. /**
  7012. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7013. */
  7014. Scalar.Lerp = function (start, end, amount) {
  7015. return start + ((end - start) * amount);
  7016. };
  7017. /**
  7018. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7019. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7020. */
  7021. Scalar.LerpAngle = function (start, end, amount) {
  7022. var num = Scalar.Repeat(end - start, 360.0);
  7023. if (num > 180.0) {
  7024. num -= 360.0;
  7025. }
  7026. return start + num * Scalar.Clamp(amount);
  7027. };
  7028. /**
  7029. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7030. */
  7031. Scalar.InverseLerp = function (a, b, value) {
  7032. var result = 0;
  7033. if (a != b) {
  7034. result = Scalar.Clamp((value - a) / (b - a));
  7035. }
  7036. else {
  7037. result = 0.0;
  7038. }
  7039. return result;
  7040. };
  7041. /**
  7042. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7043. */
  7044. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7045. var squared = amount * amount;
  7046. var cubed = amount * squared;
  7047. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7048. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7049. var part3 = (cubed - (2.0 * squared)) + amount;
  7050. var part4 = cubed - squared;
  7051. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7052. };
  7053. /**
  7054. * Returns a random float number between and min and max values
  7055. */
  7056. Scalar.RandomRange = function (min, max) {
  7057. if (min === max)
  7058. return min;
  7059. return ((Math.random() * (max - min)) + min);
  7060. };
  7061. /**
  7062. * This function returns percentage of a number in a given range.
  7063. *
  7064. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7065. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7066. */
  7067. Scalar.RangeToPercent = function (number, min, max) {
  7068. return ((number - min) / (max - min));
  7069. };
  7070. /**
  7071. * This function returns number that corresponds to the percentage in a given range.
  7072. *
  7073. * PercentToRange(0.34,0,100) will return 34.
  7074. */
  7075. Scalar.PercentToRange = function (percent, min, max) {
  7076. return ((max - min) * percent + min);
  7077. };
  7078. /**
  7079. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7080. * @param angle The angle to normalize in radian.
  7081. * @return The converted angle.
  7082. */
  7083. Scalar.NormalizeRadians = function (angle) {
  7084. // More precise but slower version kept for reference.
  7085. // angle = angle % Tools.TwoPi;
  7086. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7087. //if (angle > Math.PI) {
  7088. // angle -= Tools.TwoPi;
  7089. //}
  7090. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7091. return angle;
  7092. };
  7093. /**
  7094. * Two pi constants convenient for computation.
  7095. */
  7096. Scalar.TwoPi = Math.PI * 2;
  7097. return Scalar;
  7098. }());
  7099. BABYLON.Scalar = Scalar;
  7100. })(BABYLON || (BABYLON = {}));
  7101. //# sourceMappingURL=babylon.math.scalar.js.map
  7102. "use strict";
  7103. //# sourceMappingURL=babylon.mixins.js.map
  7104. "use strict";
  7105. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7106. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7107. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7108. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7109. //# sourceMappingURL=babylon.webgl2.js.map
  7110. "use strict";
  7111. var BABYLON;
  7112. (function (BABYLON) {
  7113. var __decoratorInitialStore = {};
  7114. var __mergedStore = {};
  7115. var _copySource = function (creationFunction, source, instanciate) {
  7116. var destination = creationFunction();
  7117. // Tags
  7118. if (BABYLON.Tags) {
  7119. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7120. }
  7121. var classStore = getMergedStore(destination);
  7122. // Properties
  7123. for (var property in classStore) {
  7124. var propertyDescriptor = classStore[property];
  7125. var sourceProperty = source[property];
  7126. var propertyType = propertyDescriptor.type;
  7127. if (sourceProperty !== undefined && sourceProperty !== null) {
  7128. switch (propertyType) {
  7129. case 0: // Value
  7130. case 6:// Mesh reference
  7131. destination[property] = sourceProperty;
  7132. break;
  7133. case 1:// Texture
  7134. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7135. break;
  7136. case 2: // Color3
  7137. case 3: // FresnelParameters
  7138. case 4: // Vector2
  7139. case 5: // Vector3
  7140. case 7: // Color Curves
  7141. case 10:// Quaternion
  7142. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7143. break;
  7144. }
  7145. }
  7146. }
  7147. return destination;
  7148. };
  7149. function getDirectStore(target) {
  7150. var classKey = target.getClassName();
  7151. if (!__decoratorInitialStore[classKey]) {
  7152. __decoratorInitialStore[classKey] = {};
  7153. }
  7154. return __decoratorInitialStore[classKey];
  7155. }
  7156. /**
  7157. * Return the list of properties flagged as serializable
  7158. * @param target: host object
  7159. */
  7160. function getMergedStore(target) {
  7161. var classKey = target.getClassName();
  7162. if (__mergedStore[classKey]) {
  7163. return __mergedStore[classKey];
  7164. }
  7165. __mergedStore[classKey] = {};
  7166. var store = __mergedStore[classKey];
  7167. var currentTarget = target;
  7168. var currentKey = classKey;
  7169. while (currentKey) {
  7170. var initialStore = __decoratorInitialStore[currentKey];
  7171. for (var property in initialStore) {
  7172. store[property] = initialStore[property];
  7173. }
  7174. var parent_1 = void 0;
  7175. var done = false;
  7176. do {
  7177. parent_1 = Object.getPrototypeOf(currentTarget);
  7178. if (!parent_1.getClassName) {
  7179. done = true;
  7180. break;
  7181. }
  7182. if (parent_1.getClassName() !== currentKey) {
  7183. break;
  7184. }
  7185. currentTarget = parent_1;
  7186. } while (parent_1);
  7187. if (done) {
  7188. break;
  7189. }
  7190. currentKey = parent_1.getClassName();
  7191. currentTarget = parent_1;
  7192. }
  7193. return store;
  7194. }
  7195. function generateSerializableMember(type, sourceName) {
  7196. return function (target, propertyKey) {
  7197. var classStore = getDirectStore(target);
  7198. if (!classStore[propertyKey]) {
  7199. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7200. }
  7201. };
  7202. }
  7203. function generateExpandMember(setCallback, targetKey) {
  7204. if (targetKey === void 0) { targetKey = null; }
  7205. return function (target, propertyKey) {
  7206. var key = targetKey || ("_" + propertyKey);
  7207. Object.defineProperty(target, propertyKey, {
  7208. get: function () {
  7209. return this[key];
  7210. },
  7211. set: function (value) {
  7212. if (this[key] === value) {
  7213. return;
  7214. }
  7215. this[key] = value;
  7216. target[setCallback].apply(this);
  7217. },
  7218. enumerable: true,
  7219. configurable: true
  7220. });
  7221. };
  7222. }
  7223. function expandToProperty(callback, targetKey) {
  7224. if (targetKey === void 0) { targetKey = null; }
  7225. return generateExpandMember(callback, targetKey);
  7226. }
  7227. BABYLON.expandToProperty = expandToProperty;
  7228. function serialize(sourceName) {
  7229. return generateSerializableMember(0, sourceName); // value member
  7230. }
  7231. BABYLON.serialize = serialize;
  7232. function serializeAsTexture(sourceName) {
  7233. return generateSerializableMember(1, sourceName); // texture member
  7234. }
  7235. BABYLON.serializeAsTexture = serializeAsTexture;
  7236. function serializeAsColor3(sourceName) {
  7237. return generateSerializableMember(2, sourceName); // color3 member
  7238. }
  7239. BABYLON.serializeAsColor3 = serializeAsColor3;
  7240. function serializeAsFresnelParameters(sourceName) {
  7241. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7242. }
  7243. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7244. function serializeAsVector2(sourceName) {
  7245. return generateSerializableMember(4, sourceName); // vector2 member
  7246. }
  7247. BABYLON.serializeAsVector2 = serializeAsVector2;
  7248. function serializeAsVector3(sourceName) {
  7249. return generateSerializableMember(5, sourceName); // vector3 member
  7250. }
  7251. BABYLON.serializeAsVector3 = serializeAsVector3;
  7252. function serializeAsMeshReference(sourceName) {
  7253. return generateSerializableMember(6, sourceName); // mesh reference member
  7254. }
  7255. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7256. function serializeAsColorCurves(sourceName) {
  7257. return generateSerializableMember(7, sourceName); // color curves
  7258. }
  7259. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7260. function serializeAsColor4(sourceName) {
  7261. return generateSerializableMember(8, sourceName); // color 4
  7262. }
  7263. BABYLON.serializeAsColor4 = serializeAsColor4;
  7264. function serializeAsImageProcessingConfiguration(sourceName) {
  7265. return generateSerializableMember(9, sourceName); // image processing
  7266. }
  7267. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7268. function serializeAsQuaternion(sourceName) {
  7269. return generateSerializableMember(10, sourceName); // quaternion member
  7270. }
  7271. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7272. var SerializationHelper = /** @class */ (function () {
  7273. function SerializationHelper() {
  7274. }
  7275. SerializationHelper.Serialize = function (entity, serializationObject) {
  7276. if (!serializationObject) {
  7277. serializationObject = {};
  7278. }
  7279. // Tags
  7280. if (BABYLON.Tags) {
  7281. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7282. }
  7283. var serializedProperties = getMergedStore(entity);
  7284. // Properties
  7285. for (var property in serializedProperties) {
  7286. var propertyDescriptor = serializedProperties[property];
  7287. var targetPropertyName = propertyDescriptor.sourceName || property;
  7288. var propertyType = propertyDescriptor.type;
  7289. var sourceProperty = entity[property];
  7290. if (sourceProperty !== undefined && sourceProperty !== null) {
  7291. switch (propertyType) {
  7292. case 0:// Value
  7293. serializationObject[targetPropertyName] = sourceProperty;
  7294. break;
  7295. case 1:// Texture
  7296. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7297. break;
  7298. case 2:// Color3
  7299. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7300. break;
  7301. case 3:// FresnelParameters
  7302. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7303. break;
  7304. case 4:// Vector2
  7305. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7306. break;
  7307. case 5:// Vector3
  7308. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7309. break;
  7310. case 6:// Mesh reference
  7311. serializationObject[targetPropertyName] = sourceProperty.id;
  7312. break;
  7313. case 7:// Color Curves
  7314. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7315. break;
  7316. case 8:// Color 4
  7317. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7318. break;
  7319. case 9:// Image Processing
  7320. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7321. break;
  7322. }
  7323. }
  7324. }
  7325. return serializationObject;
  7326. };
  7327. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7328. if (rootUrl === void 0) { rootUrl = null; }
  7329. var destination = creationFunction();
  7330. if (!rootUrl) {
  7331. rootUrl = "";
  7332. }
  7333. // Tags
  7334. if (BABYLON.Tags) {
  7335. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7336. }
  7337. var classStore = getMergedStore(destination);
  7338. // Properties
  7339. for (var property in classStore) {
  7340. var propertyDescriptor = classStore[property];
  7341. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7342. var propertyType = propertyDescriptor.type;
  7343. if (sourceProperty !== undefined && sourceProperty !== null) {
  7344. var dest = destination;
  7345. switch (propertyType) {
  7346. case 0:// Value
  7347. dest[property] = sourceProperty;
  7348. break;
  7349. case 1:// Texture
  7350. if (scene) {
  7351. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7352. }
  7353. break;
  7354. case 2:// Color3
  7355. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7356. break;
  7357. case 3:// FresnelParameters
  7358. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7359. break;
  7360. case 4:// Vector2
  7361. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7362. break;
  7363. case 5:// Vector3
  7364. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7365. break;
  7366. case 6:// Mesh reference
  7367. if (scene) {
  7368. dest[property] = scene.getLastMeshByID(sourceProperty);
  7369. }
  7370. break;
  7371. case 7:// Color Curves
  7372. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7373. break;
  7374. case 8:// Color 4
  7375. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7376. break;
  7377. case 9:// Image Processing
  7378. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7379. break;
  7380. }
  7381. }
  7382. }
  7383. return destination;
  7384. };
  7385. SerializationHelper.Clone = function (creationFunction, source) {
  7386. return _copySource(creationFunction, source, false);
  7387. };
  7388. SerializationHelper.Instanciate = function (creationFunction, source) {
  7389. return _copySource(creationFunction, source, true);
  7390. };
  7391. return SerializationHelper;
  7392. }());
  7393. BABYLON.SerializationHelper = SerializationHelper;
  7394. })(BABYLON || (BABYLON = {}));
  7395. //# sourceMappingURL=babylon.decorators.js.map
  7396. "use strict";
  7397. var BABYLON;
  7398. (function (BABYLON) {
  7399. /**
  7400. * Wrapper class for promise with external resolve and reject.
  7401. */
  7402. var Deferred = /** @class */ (function () {
  7403. /**
  7404. * Constructor for this deferred object.
  7405. */
  7406. function Deferred() {
  7407. var _this = this;
  7408. this.promise = new Promise(function (resolve, reject) {
  7409. _this._resolve = resolve;
  7410. _this._reject = reject;
  7411. });
  7412. }
  7413. Object.defineProperty(Deferred.prototype, "resolve", {
  7414. /**
  7415. * The resolve method of the promise associated with this deferred object.
  7416. */
  7417. get: function () {
  7418. return this._resolve;
  7419. },
  7420. enumerable: true,
  7421. configurable: true
  7422. });
  7423. Object.defineProperty(Deferred.prototype, "reject", {
  7424. /**
  7425. * The reject method of the promise associated with this deferred object.
  7426. */
  7427. get: function () {
  7428. return this._reject;
  7429. },
  7430. enumerable: true,
  7431. configurable: true
  7432. });
  7433. return Deferred;
  7434. }());
  7435. BABYLON.Deferred = Deferred;
  7436. })(BABYLON || (BABYLON = {}));
  7437. //# sourceMappingURL=babylon.deferred.js.map
  7438. "use strict";
  7439. var BABYLON;
  7440. (function (BABYLON) {
  7441. /**
  7442. * A class serves as a medium between the observable and its observers
  7443. */
  7444. var EventState = /** @class */ (function () {
  7445. /**
  7446. * Create a new EventState
  7447. * @param mask defines the mask associated with this state
  7448. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7449. * @param target defines the original target of the state
  7450. * @param currentTarget defines the current target of the state
  7451. */
  7452. function EventState(mask, skipNextObservers, target, currentTarget) {
  7453. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7454. this.initalize(mask, skipNextObservers, target, currentTarget);
  7455. }
  7456. /**
  7457. * Initialize the current event state
  7458. * @param mask defines the mask associated with this state
  7459. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7460. * @param target defines the original target of the state
  7461. * @param currentTarget defines the current target of the state
  7462. * @returns the current event state
  7463. */
  7464. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  7465. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7466. this.mask = mask;
  7467. this.skipNextObservers = skipNextObservers;
  7468. this.target = target;
  7469. this.currentTarget = currentTarget;
  7470. return this;
  7471. };
  7472. return EventState;
  7473. }());
  7474. BABYLON.EventState = EventState;
  7475. /**
  7476. * Represent an Observer registered to a given Observable object.
  7477. */
  7478. var Observer = /** @class */ (function () {
  7479. /**
  7480. * Creates a new observer
  7481. * @param callback defines the callback to call when the observer is notified
  7482. * @param mask defines the mask of the observer (used to filter notifications)
  7483. * @param scope defines the current scope used to restore the JS context
  7484. */
  7485. function Observer(
  7486. /**
  7487. * Defines the callback to call when the observer is notified
  7488. */
  7489. callback,
  7490. /**
  7491. * Defines the mask of the observer (used to filter notifications)
  7492. */
  7493. mask,
  7494. /**
  7495. * Defines the current scope used to restore the JS context
  7496. */
  7497. scope) {
  7498. if (scope === void 0) { scope = null; }
  7499. this.callback = callback;
  7500. this.mask = mask;
  7501. this.scope = scope;
  7502. /** @ignore */
  7503. this._willBeUnregistered = false;
  7504. /**
  7505. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  7506. */
  7507. this.unregisterOnNextCall = false;
  7508. }
  7509. return Observer;
  7510. }());
  7511. BABYLON.Observer = Observer;
  7512. /**
  7513. * Represent a list of observers registered to multiple Observables object.
  7514. */
  7515. var MultiObserver = /** @class */ (function () {
  7516. function MultiObserver() {
  7517. }
  7518. /**
  7519. * Release associated resources
  7520. */
  7521. MultiObserver.prototype.dispose = function () {
  7522. if (this._observers && this._observables) {
  7523. for (var index = 0; index < this._observers.length; index++) {
  7524. this._observables[index].remove(this._observers[index]);
  7525. }
  7526. }
  7527. this._observers = null;
  7528. this._observables = null;
  7529. };
  7530. /**
  7531. * Raise a callback when one of the observable will notify
  7532. * @param observables defines a list of observables to watch
  7533. * @param callback defines the callback to call on notification
  7534. * @param mask defines the mask used to filter notifications
  7535. * @param scope defines the current scope used to restore the JS context
  7536. * @returns the new MultiObserver
  7537. */
  7538. MultiObserver.Watch = function (observables, callback, mask, scope) {
  7539. if (mask === void 0) { mask = -1; }
  7540. if (scope === void 0) { scope = null; }
  7541. var result = new MultiObserver();
  7542. result._observers = new Array();
  7543. result._observables = observables;
  7544. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  7545. var observable = observables_1[_i];
  7546. var observer = observable.add(callback, mask, false, scope);
  7547. if (observer) {
  7548. result._observers.push(observer);
  7549. }
  7550. }
  7551. return result;
  7552. };
  7553. return MultiObserver;
  7554. }());
  7555. BABYLON.MultiObserver = MultiObserver;
  7556. /**
  7557. * The Observable class is a simple implementation of the Observable pattern.
  7558. * 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.
  7559. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  7560. * 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).
  7561. * 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.
  7562. */
  7563. var Observable = /** @class */ (function () {
  7564. /**
  7565. * Creates a new observable
  7566. * @param onObserverAdded defines a callback to call when a new observer is added
  7567. */
  7568. function Observable(onObserverAdded) {
  7569. this._observers = new Array();
  7570. this._eventState = new EventState(0);
  7571. if (onObserverAdded) {
  7572. this._onObserverAdded = onObserverAdded;
  7573. }
  7574. }
  7575. /**
  7576. * Create a new Observer with the specified callback
  7577. * @param callback the callback that will be executed for that Observer
  7578. * @param mask the mask used to filter observers
  7579. * @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.
  7580. * @param scope optional scope for the callback to be called from
  7581. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  7582. * @returns the new observer created for the callback
  7583. */
  7584. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  7585. if (mask === void 0) { mask = -1; }
  7586. if (insertFirst === void 0) { insertFirst = false; }
  7587. if (scope === void 0) { scope = null; }
  7588. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  7589. if (!callback) {
  7590. return null;
  7591. }
  7592. var observer = new Observer(callback, mask, scope);
  7593. observer.unregisterOnNextCall = unregisterOnFirstCall;
  7594. if (insertFirst) {
  7595. this._observers.unshift(observer);
  7596. }
  7597. else {
  7598. this._observers.push(observer);
  7599. }
  7600. if (this._onObserverAdded) {
  7601. this._onObserverAdded(observer);
  7602. }
  7603. return observer;
  7604. };
  7605. /**
  7606. * Remove an Observer from the Observable object
  7607. * @param observer the instance of the Observer to remove
  7608. * @returns false if it doesn't belong to this Observable
  7609. */
  7610. Observable.prototype.remove = function (observer) {
  7611. if (!observer) {
  7612. return false;
  7613. }
  7614. var index = this._observers.indexOf(observer);
  7615. if (index !== -1) {
  7616. this._observers.splice(index, 1);
  7617. return true;
  7618. }
  7619. return false;
  7620. };
  7621. /**
  7622. * Remove a callback from the Observable object
  7623. * @param callback the callback to remove
  7624. * @param scope optional scope. If used only the callbacks with this scope will be removed
  7625. * @returns false if it doesn't belong to this Observable
  7626. */
  7627. Observable.prototype.removeCallback = function (callback, scope) {
  7628. for (var index = 0; index < this._observers.length; index++) {
  7629. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  7630. this._observers.splice(index, 1);
  7631. return true;
  7632. }
  7633. }
  7634. return false;
  7635. };
  7636. Observable.prototype._deferUnregister = function (observer) {
  7637. var _this = this;
  7638. observer.unregisterOnNextCall = false;
  7639. observer._willBeUnregistered = true;
  7640. BABYLON.Tools.SetImmediate(function () {
  7641. _this.remove(observer);
  7642. });
  7643. };
  7644. /**
  7645. * Notify all Observers by calling their respective callback with the given data
  7646. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  7647. * @param eventData defines the data to send to all observers
  7648. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  7649. * @param target defines the original target of the state
  7650. * @param currentTarget defines the current target of the state
  7651. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  7652. */
  7653. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  7654. if (mask === void 0) { mask = -1; }
  7655. if (!this._observers.length) {
  7656. return true;
  7657. }
  7658. var state = this._eventState;
  7659. state.mask = mask;
  7660. state.target = target;
  7661. state.currentTarget = currentTarget;
  7662. state.skipNextObservers = false;
  7663. state.lastReturnValue = eventData;
  7664. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7665. var obs = _a[_i];
  7666. if (obs._willBeUnregistered) {
  7667. continue;
  7668. }
  7669. if (obs.mask & mask) {
  7670. if (obs.scope) {
  7671. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  7672. }
  7673. else {
  7674. state.lastReturnValue = obs.callback(eventData, state);
  7675. }
  7676. if (obs.unregisterOnNextCall) {
  7677. this._deferUnregister(obs);
  7678. }
  7679. }
  7680. if (state.skipNextObservers) {
  7681. return false;
  7682. }
  7683. }
  7684. return true;
  7685. };
  7686. /**
  7687. * Calling this will execute each callback, expecting it to be a promise or return a value.
  7688. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  7689. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  7690. * and it is crucial that all callbacks will be executed.
  7691. * The order of the callbacks is kept, callbacks are not executed parallel.
  7692. *
  7693. * @param eventData The data to be sent to each callback
  7694. * @param mask is used to filter observers defaults to -1
  7695. * @param target defines the callback target (see EventState)
  7696. * @param currentTarget defines he current object in the bubbling phase
  7697. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  7698. */
  7699. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  7700. var _this = this;
  7701. if (mask === void 0) { mask = -1; }
  7702. // create an empty promise
  7703. var p = Promise.resolve(eventData);
  7704. // no observers? return this promise.
  7705. if (!this._observers.length) {
  7706. return p;
  7707. }
  7708. var state = this._eventState;
  7709. state.mask = mask;
  7710. state.target = target;
  7711. state.currentTarget = currentTarget;
  7712. state.skipNextObservers = false;
  7713. // execute one callback after another (not using Promise.all, the order is important)
  7714. this._observers.forEach(function (obs) {
  7715. if (state.skipNextObservers) {
  7716. return;
  7717. }
  7718. if (obs._willBeUnregistered) {
  7719. return;
  7720. }
  7721. if (obs.mask & mask) {
  7722. if (obs.scope) {
  7723. p = p.then(function (lastReturnedValue) {
  7724. state.lastReturnValue = lastReturnedValue;
  7725. return obs.callback.apply(obs.scope, [eventData, state]);
  7726. });
  7727. }
  7728. else {
  7729. p = p.then(function (lastReturnedValue) {
  7730. state.lastReturnValue = lastReturnedValue;
  7731. return obs.callback(eventData, state);
  7732. });
  7733. }
  7734. if (obs.unregisterOnNextCall) {
  7735. _this._deferUnregister(obs);
  7736. }
  7737. }
  7738. });
  7739. // return the eventData
  7740. return p.then(function () { return eventData; });
  7741. };
  7742. /**
  7743. * Notify a specific observer
  7744. * @param observer defines the observer to notify
  7745. * @param eventData defines the data to be sent to each callback
  7746. * @param mask is used to filter observers defaults to -1
  7747. */
  7748. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  7749. if (mask === void 0) { mask = -1; }
  7750. var state = this._eventState;
  7751. state.mask = mask;
  7752. state.skipNextObservers = false;
  7753. observer.callback(eventData, state);
  7754. };
  7755. /**
  7756. * Gets a boolean indicating if the observable has at least one observer
  7757. * @returns true is the Observable has at least one Observer registered
  7758. */
  7759. Observable.prototype.hasObservers = function () {
  7760. return this._observers.length > 0;
  7761. };
  7762. /**
  7763. * Clear the list of observers
  7764. */
  7765. Observable.prototype.clear = function () {
  7766. this._observers = new Array();
  7767. this._onObserverAdded = null;
  7768. };
  7769. /**
  7770. * Clone the current observable
  7771. * @returns a new observable
  7772. */
  7773. Observable.prototype.clone = function () {
  7774. var result = new Observable();
  7775. result._observers = this._observers.slice(0);
  7776. return result;
  7777. };
  7778. /**
  7779. * Does this observable handles observer registered with a given mask
  7780. * @param mask defines the mask to be tested
  7781. * @return whether or not one observer registered with the given mask is handeled
  7782. **/
  7783. Observable.prototype.hasSpecificMask = function (mask) {
  7784. if (mask === void 0) { mask = -1; }
  7785. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  7786. var obs = _a[_i];
  7787. if (obs.mask & mask || obs.mask === mask) {
  7788. return true;
  7789. }
  7790. }
  7791. return false;
  7792. };
  7793. return Observable;
  7794. }());
  7795. BABYLON.Observable = Observable;
  7796. })(BABYLON || (BABYLON = {}));
  7797. //# sourceMappingURL=babylon.observable.js.map
  7798. "use strict";
  7799. var BABYLON;
  7800. (function (BABYLON) {
  7801. var SmartArray = /** @class */ (function () {
  7802. function SmartArray(capacity) {
  7803. this.length = 0;
  7804. this.data = new Array(capacity);
  7805. this._id = SmartArray._GlobalId++;
  7806. }
  7807. SmartArray.prototype.push = function (value) {
  7808. this.data[this.length++] = value;
  7809. if (this.length > this.data.length) {
  7810. this.data.length *= 2;
  7811. }
  7812. };
  7813. SmartArray.prototype.forEach = function (func) {
  7814. for (var index = 0; index < this.length; index++) {
  7815. func(this.data[index]);
  7816. }
  7817. };
  7818. SmartArray.prototype.sort = function (compareFn) {
  7819. this.data.sort(compareFn);
  7820. };
  7821. SmartArray.prototype.reset = function () {
  7822. this.length = 0;
  7823. };
  7824. SmartArray.prototype.dispose = function () {
  7825. this.reset();
  7826. if (this.data) {
  7827. this.data.length = 0;
  7828. this.data = [];
  7829. }
  7830. };
  7831. SmartArray.prototype.concat = function (array) {
  7832. if (array.length === 0) {
  7833. return;
  7834. }
  7835. if (this.length + array.length > this.data.length) {
  7836. this.data.length = (this.length + array.length) * 2;
  7837. }
  7838. for (var index = 0; index < array.length; index++) {
  7839. this.data[this.length++] = (array.data || array)[index];
  7840. }
  7841. };
  7842. SmartArray.prototype.indexOf = function (value) {
  7843. var position = this.data.indexOf(value);
  7844. if (position >= this.length) {
  7845. return -1;
  7846. }
  7847. return position;
  7848. };
  7849. SmartArray.prototype.contains = function (value) {
  7850. return this.data.indexOf(value) !== -1;
  7851. };
  7852. // Statics
  7853. SmartArray._GlobalId = 0;
  7854. return SmartArray;
  7855. }());
  7856. BABYLON.SmartArray = SmartArray;
  7857. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  7858. __extends(SmartArrayNoDuplicate, _super);
  7859. function SmartArrayNoDuplicate() {
  7860. var _this = _super !== null && _super.apply(this, arguments) || this;
  7861. _this._duplicateId = 0;
  7862. return _this;
  7863. }
  7864. SmartArrayNoDuplicate.prototype.push = function (value) {
  7865. _super.prototype.push.call(this, value);
  7866. if (!value.__smartArrayFlags) {
  7867. value.__smartArrayFlags = {};
  7868. }
  7869. value.__smartArrayFlags[this._id] = this._duplicateId;
  7870. };
  7871. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  7872. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  7873. return false;
  7874. }
  7875. this.push(value);
  7876. return true;
  7877. };
  7878. SmartArrayNoDuplicate.prototype.reset = function () {
  7879. _super.prototype.reset.call(this);
  7880. this._duplicateId++;
  7881. };
  7882. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  7883. if (array.length === 0) {
  7884. return;
  7885. }
  7886. if (this.length + array.length > this.data.length) {
  7887. this.data.length = (this.length + array.length) * 2;
  7888. }
  7889. for (var index = 0; index < array.length; index++) {
  7890. var item = (array.data || array)[index];
  7891. this.pushNoDuplicate(item);
  7892. }
  7893. };
  7894. return SmartArrayNoDuplicate;
  7895. }(SmartArray));
  7896. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  7897. })(BABYLON || (BABYLON = {}));
  7898. //# sourceMappingURL=babylon.smartArray.js.map
  7899. "use strict";
  7900. var BABYLON;
  7901. (function (BABYLON) {
  7902. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  7903. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  7904. var LoadFileError = /** @class */ (function (_super) {
  7905. __extends(LoadFileError, _super);
  7906. function LoadFileError(message, request) {
  7907. var _this = _super.call(this, message) || this;
  7908. _this.request = request;
  7909. _this.name = "LoadFileError";
  7910. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  7911. return _this;
  7912. }
  7913. // Polyfill for Object.setPrototypeOf if necessary.
  7914. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  7915. return LoadFileError;
  7916. }(Error));
  7917. BABYLON.LoadFileError = LoadFileError;
  7918. var RetryStrategy = /** @class */ (function () {
  7919. function RetryStrategy() {
  7920. }
  7921. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  7922. if (maxRetries === void 0) { maxRetries = 3; }
  7923. if (baseInterval === void 0) { baseInterval = 500; }
  7924. return function (url, request, retryIndex) {
  7925. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  7926. return -1;
  7927. }
  7928. return Math.pow(2, retryIndex) * baseInterval;
  7929. };
  7930. };
  7931. return RetryStrategy;
  7932. }());
  7933. BABYLON.RetryStrategy = RetryStrategy;
  7934. // Screenshots
  7935. var screenshotCanvas;
  7936. var cloneValue = function (source, destinationObject) {
  7937. if (!source)
  7938. return null;
  7939. if (source instanceof BABYLON.Mesh) {
  7940. return null;
  7941. }
  7942. if (source instanceof BABYLON.SubMesh) {
  7943. return source.clone(destinationObject);
  7944. }
  7945. else if (source.clone) {
  7946. return source.clone();
  7947. }
  7948. return null;
  7949. };
  7950. var Tools = /** @class */ (function () {
  7951. function Tools() {
  7952. }
  7953. /**
  7954. * Interpolates between a and b via alpha
  7955. * @param a The lower value (returned when alpha = 0)
  7956. * @param b The upper value (returned when alpha = 1)
  7957. * @param alpha The interpolation-factor
  7958. * @return The mixed value
  7959. */
  7960. Tools.Mix = function (a, b, alpha) {
  7961. return a * (1 - alpha) + b * alpha;
  7962. };
  7963. Tools.Instantiate = function (className) {
  7964. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  7965. return Tools.RegisteredExternalClasses[className];
  7966. }
  7967. var arr = className.split(".");
  7968. var fn = (window || this);
  7969. for (var i = 0, len = arr.length; i < len; i++) {
  7970. fn = fn[arr[i]];
  7971. }
  7972. if (typeof fn !== "function") {
  7973. return null;
  7974. }
  7975. return fn;
  7976. };
  7977. /**
  7978. * Provides a slice function that will work even on IE
  7979. * @param data defines the array to slice
  7980. * @returns the new sliced array
  7981. */
  7982. Tools.Slice = function (data) {
  7983. if (data.slice) {
  7984. return data.slice();
  7985. }
  7986. return Array.prototype.slice.call(data);
  7987. };
  7988. Tools.SetImmediate = function (action) {
  7989. if (window.setImmediate) {
  7990. window.setImmediate(action);
  7991. }
  7992. else {
  7993. setTimeout(action, 1);
  7994. }
  7995. };
  7996. Tools.IsExponentOfTwo = function (value) {
  7997. var count = 1;
  7998. do {
  7999. count *= 2;
  8000. } while (count < value);
  8001. return count === value;
  8002. };
  8003. /**
  8004. * Find the next highest power of two.
  8005. * @param x Number to start search from.
  8006. * @return Next highest power of two.
  8007. */
  8008. Tools.CeilingPOT = function (x) {
  8009. x--;
  8010. x |= x >> 1;
  8011. x |= x >> 2;
  8012. x |= x >> 4;
  8013. x |= x >> 8;
  8014. x |= x >> 16;
  8015. x++;
  8016. return x;
  8017. };
  8018. /**
  8019. * Find the next lowest power of two.
  8020. * @param x Number to start search from.
  8021. * @return Next lowest power of two.
  8022. */
  8023. Tools.FloorPOT = function (x) {
  8024. x = x | (x >> 1);
  8025. x = x | (x >> 2);
  8026. x = x | (x >> 4);
  8027. x = x | (x >> 8);
  8028. x = x | (x >> 16);
  8029. return x - (x >> 1);
  8030. };
  8031. /**
  8032. * Find the nearest power of two.
  8033. * @param x Number to start search from.
  8034. * @return Next nearest power of two.
  8035. */
  8036. Tools.NearestPOT = function (x) {
  8037. var c = Tools.CeilingPOT(x);
  8038. var f = Tools.FloorPOT(x);
  8039. return (c - x) > (x - f) ? f : c;
  8040. };
  8041. Tools.GetExponentOfTwo = function (value, max, mode) {
  8042. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8043. var pot;
  8044. switch (mode) {
  8045. case BABYLON.Engine.SCALEMODE_FLOOR:
  8046. pot = Tools.FloorPOT(value);
  8047. break;
  8048. case BABYLON.Engine.SCALEMODE_NEAREST:
  8049. pot = Tools.NearestPOT(value);
  8050. break;
  8051. case BABYLON.Engine.SCALEMODE_CEILING:
  8052. default:
  8053. pot = Tools.CeilingPOT(value);
  8054. break;
  8055. }
  8056. return Math.min(pot, max);
  8057. };
  8058. Tools.GetFilename = function (path) {
  8059. var index = path.lastIndexOf("/");
  8060. if (index < 0)
  8061. return path;
  8062. return path.substring(index + 1);
  8063. };
  8064. /**
  8065. * Extracts the "folder" part of a path (everything before the filename).
  8066. * @param uri The URI to extract the info from
  8067. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8068. * @returns The "folder" part of the path
  8069. */
  8070. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8071. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8072. var index = uri.lastIndexOf("/");
  8073. if (index < 0) {
  8074. if (returnUnchangedIfNoSlash) {
  8075. return uri;
  8076. }
  8077. return "";
  8078. }
  8079. return uri.substring(0, index + 1);
  8080. };
  8081. Tools.GetDOMTextContent = function (element) {
  8082. var result = "";
  8083. var child = element.firstChild;
  8084. while (child) {
  8085. if (child.nodeType === 3) {
  8086. result += child.textContent;
  8087. }
  8088. child = child.nextSibling;
  8089. }
  8090. return result;
  8091. };
  8092. Tools.ToDegrees = function (angle) {
  8093. return angle * 180 / Math.PI;
  8094. };
  8095. Tools.ToRadians = function (angle) {
  8096. return angle * Math.PI / 180;
  8097. };
  8098. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8099. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8100. var output = "";
  8101. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8102. var i = 0;
  8103. var bytes = new Uint8Array(buffer);
  8104. while (i < bytes.length) {
  8105. chr1 = bytes[i++];
  8106. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8107. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8108. enc1 = chr1 >> 2;
  8109. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8110. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8111. enc4 = chr3 & 63;
  8112. if (isNaN(chr2)) {
  8113. enc3 = enc4 = 64;
  8114. }
  8115. else if (isNaN(chr3)) {
  8116. enc4 = 64;
  8117. }
  8118. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8119. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8120. }
  8121. return "data:image/png;base64," + output;
  8122. };
  8123. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8124. if (bias === void 0) { bias = null; }
  8125. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8126. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8127. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8128. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8129. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8130. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8131. }
  8132. if (bias) {
  8133. minimum.x -= minimum.x * bias.x + bias.y;
  8134. minimum.y -= minimum.y * bias.x + bias.y;
  8135. minimum.z -= minimum.z * bias.x + bias.y;
  8136. maximum.x += maximum.x * bias.x + bias.y;
  8137. maximum.y += maximum.y * bias.x + bias.y;
  8138. maximum.z += maximum.z * bias.x + bias.y;
  8139. }
  8140. return {
  8141. minimum: minimum,
  8142. maximum: maximum
  8143. };
  8144. };
  8145. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8146. if (bias === void 0) { bias = null; }
  8147. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8148. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8149. if (!stride) {
  8150. stride = 3;
  8151. }
  8152. for (var index = start; index < start + count; index++) {
  8153. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8154. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8155. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8156. }
  8157. if (bias) {
  8158. minimum.x -= minimum.x * bias.x + bias.y;
  8159. minimum.y -= minimum.y * bias.x + bias.y;
  8160. minimum.z -= minimum.z * bias.x + bias.y;
  8161. maximum.x += maximum.x * bias.x + bias.y;
  8162. maximum.y += maximum.y * bias.x + bias.y;
  8163. maximum.z += maximum.z * bias.x + bias.y;
  8164. }
  8165. return {
  8166. minimum: minimum,
  8167. maximum: maximum
  8168. };
  8169. };
  8170. Tools.Vector2ArrayFeeder = function (array) {
  8171. return function (index) {
  8172. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8173. var length = isFloatArray ? array.length / 2 : array.length;
  8174. if (index >= length) {
  8175. return null;
  8176. }
  8177. if (isFloatArray) {
  8178. var fa = array;
  8179. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8180. }
  8181. var a = array;
  8182. return a[index];
  8183. };
  8184. };
  8185. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8186. if (bias === void 0) { bias = null; }
  8187. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8188. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8189. var i = 0;
  8190. var cur = feeder(i++);
  8191. while (cur) {
  8192. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8193. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8194. cur = feeder(i++);
  8195. }
  8196. if (bias) {
  8197. minimum.x -= minimum.x * bias.x + bias.y;
  8198. minimum.y -= minimum.y * bias.x + bias.y;
  8199. maximum.x += maximum.x * bias.x + bias.y;
  8200. maximum.y += maximum.y * bias.x + bias.y;
  8201. }
  8202. return {
  8203. minimum: minimum,
  8204. maximum: maximum
  8205. };
  8206. };
  8207. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8208. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8209. return null;
  8210. return Array.isArray(obj) ? obj : [obj];
  8211. };
  8212. // Misc.
  8213. Tools.GetPointerPrefix = function () {
  8214. var eventPrefix = "pointer";
  8215. // Check if pointer events are supported
  8216. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8217. eventPrefix = "mouse";
  8218. }
  8219. return eventPrefix;
  8220. };
  8221. /**
  8222. * @param func - the function to be called
  8223. * @param requester - the object that will request the next frame. Falls back to window.
  8224. */
  8225. Tools.QueueNewFrame = function (func, requester) {
  8226. if (!Tools.IsWindowObjectExist()) {
  8227. return setTimeout(func, 16);
  8228. }
  8229. if (!requester) {
  8230. requester = window;
  8231. }
  8232. if (requester.requestAnimationFrame) {
  8233. return requester.requestAnimationFrame(func);
  8234. }
  8235. else if (requester.msRequestAnimationFrame) {
  8236. return requester.msRequestAnimationFrame(func);
  8237. }
  8238. else if (requester.webkitRequestAnimationFrame) {
  8239. return requester.webkitRequestAnimationFrame(func);
  8240. }
  8241. else if (requester.mozRequestAnimationFrame) {
  8242. return requester.mozRequestAnimationFrame(func);
  8243. }
  8244. else if (requester.oRequestAnimationFrame) {
  8245. return requester.oRequestAnimationFrame(func);
  8246. }
  8247. else {
  8248. return window.setTimeout(func, 16);
  8249. }
  8250. };
  8251. Tools.RequestFullscreen = function (element) {
  8252. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8253. if (!requestFunction)
  8254. return;
  8255. requestFunction.call(element);
  8256. };
  8257. Tools.ExitFullscreen = function () {
  8258. if (document.exitFullscreen) {
  8259. document.exitFullscreen();
  8260. }
  8261. else if (document.mozCancelFullScreen) {
  8262. document.mozCancelFullScreen();
  8263. }
  8264. else if (document.webkitCancelFullScreen) {
  8265. document.webkitCancelFullScreen();
  8266. }
  8267. else if (document.msCancelFullScreen) {
  8268. document.msCancelFullScreen();
  8269. }
  8270. };
  8271. Tools.SetCorsBehavior = function (url, element) {
  8272. if (url && url.indexOf("data:") === 0) {
  8273. return;
  8274. }
  8275. if (Tools.CorsBehavior) {
  8276. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8277. element.crossOrigin = Tools.CorsBehavior;
  8278. }
  8279. else {
  8280. var result = Tools.CorsBehavior(url);
  8281. if (result) {
  8282. element.crossOrigin = result;
  8283. }
  8284. }
  8285. }
  8286. };
  8287. // External files
  8288. Tools.CleanUrl = function (url) {
  8289. url = url.replace(/#/mg, "%23");
  8290. return url;
  8291. };
  8292. Tools.LoadImage = function (url, onLoad, onError, database) {
  8293. if (url instanceof ArrayBuffer) {
  8294. url = Tools.EncodeArrayBufferTobase64(url);
  8295. }
  8296. url = Tools.CleanUrl(url);
  8297. url = Tools.PreprocessUrl(url);
  8298. var img = new Image();
  8299. Tools.SetCorsBehavior(url, img);
  8300. var loadHandler = function () {
  8301. img.removeEventListener("load", loadHandler);
  8302. img.removeEventListener("error", errorHandler);
  8303. onLoad(img);
  8304. };
  8305. var errorHandler = function (err) {
  8306. img.removeEventListener("load", loadHandler);
  8307. img.removeEventListener("error", errorHandler);
  8308. Tools.Error("Error while trying to load image: " + url);
  8309. if (onError) {
  8310. onError("Error while trying to load image: " + url, err);
  8311. }
  8312. };
  8313. img.addEventListener("load", loadHandler);
  8314. img.addEventListener("error", errorHandler);
  8315. var noIndexedDB = function () {
  8316. img.src = url;
  8317. };
  8318. var loadFromIndexedDB = function () {
  8319. if (database) {
  8320. database.loadImageFromDB(url, img);
  8321. }
  8322. };
  8323. //ANY database to do!
  8324. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8325. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8326. }
  8327. else {
  8328. if (url.indexOf("file:") !== -1) {
  8329. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8330. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8331. try {
  8332. var blobURL;
  8333. try {
  8334. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8335. }
  8336. catch (ex) {
  8337. // Chrome doesn't support oneTimeOnly parameter
  8338. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8339. }
  8340. img.src = blobURL;
  8341. }
  8342. catch (e) {
  8343. img.src = "";
  8344. }
  8345. return img;
  8346. }
  8347. }
  8348. noIndexedDB();
  8349. }
  8350. return img;
  8351. };
  8352. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8353. url = Tools.CleanUrl(url);
  8354. url = Tools.PreprocessUrl(url);
  8355. // If file and file input are set
  8356. if (url.indexOf("file:") !== -1) {
  8357. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8358. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8359. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8360. }
  8361. }
  8362. var loadUrl = Tools.BaseUrl + url;
  8363. var aborted = false;
  8364. var fileRequest = {
  8365. onCompleteObservable: new BABYLON.Observable(),
  8366. abort: function () { return aborted = true; },
  8367. };
  8368. var requestFile = function () {
  8369. var request = new XMLHttpRequest();
  8370. var retryHandle = null;
  8371. fileRequest.abort = function () {
  8372. aborted = true;
  8373. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8374. request.abort();
  8375. }
  8376. if (retryHandle !== null) {
  8377. clearTimeout(retryHandle);
  8378. retryHandle = null;
  8379. }
  8380. };
  8381. var retryLoop = function (retryIndex) {
  8382. request.open('GET', loadUrl, true);
  8383. if (useArrayBuffer) {
  8384. request.responseType = "arraybuffer";
  8385. }
  8386. if (onProgress) {
  8387. request.addEventListener("progress", onProgress);
  8388. }
  8389. var onLoadEnd = function () {
  8390. request.removeEventListener("loadend", onLoadEnd);
  8391. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8392. fileRequest.onCompleteObservable.clear();
  8393. };
  8394. request.addEventListener("loadend", onLoadEnd);
  8395. var onReadyStateChange = function () {
  8396. if (aborted) {
  8397. return;
  8398. }
  8399. // In case of undefined state in some browsers.
  8400. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8401. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8402. request.removeEventListener("readystatechange", onReadyStateChange);
  8403. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8404. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8405. return;
  8406. }
  8407. var retryStrategy = Tools.DefaultRetryStrategy;
  8408. if (retryStrategy) {
  8409. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8410. if (waitTime !== -1) {
  8411. // Prevent the request from completing for retry.
  8412. request.removeEventListener("loadend", onLoadEnd);
  8413. request = new XMLHttpRequest();
  8414. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8415. return;
  8416. }
  8417. }
  8418. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8419. if (onError) {
  8420. onError(request, e);
  8421. }
  8422. else {
  8423. throw e;
  8424. }
  8425. }
  8426. };
  8427. request.addEventListener("readystatechange", onReadyStateChange);
  8428. request.send();
  8429. };
  8430. retryLoop(0);
  8431. };
  8432. // Caching all files
  8433. if (database && database.enableSceneOffline) {
  8434. var noIndexedDB_1 = function () {
  8435. if (!aborted) {
  8436. requestFile();
  8437. }
  8438. };
  8439. var loadFromIndexedDB = function () {
  8440. // TODO: database needs to support aborting and should return a IFileRequest
  8441. if (aborted) {
  8442. return;
  8443. }
  8444. if (database) {
  8445. database.loadFileFromDB(url, function (data) {
  8446. if (!aborted) {
  8447. onSuccess(data);
  8448. }
  8449. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8450. }, onProgress ? function (event) {
  8451. if (!aborted) {
  8452. onProgress(event);
  8453. }
  8454. } : undefined, noIndexedDB_1, useArrayBuffer);
  8455. }
  8456. };
  8457. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  8458. }
  8459. else {
  8460. requestFile();
  8461. }
  8462. return fileRequest;
  8463. };
  8464. /**
  8465. * Load a script (identified by an url). When the url returns, the
  8466. * content of this file is added into a new script element, attached to the DOM (body element)
  8467. */
  8468. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  8469. var head = document.getElementsByTagName('head')[0];
  8470. var script = document.createElement('script');
  8471. script.type = 'text/javascript';
  8472. script.src = scriptUrl;
  8473. script.onload = function () {
  8474. if (onSuccess) {
  8475. onSuccess();
  8476. }
  8477. };
  8478. script.onerror = function (e) {
  8479. if (onError) {
  8480. onError("Unable to load script", e);
  8481. }
  8482. };
  8483. head.appendChild(script);
  8484. };
  8485. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  8486. var reader = new FileReader();
  8487. var request = {
  8488. onCompleteObservable: new BABYLON.Observable(),
  8489. abort: function () { return reader.abort(); },
  8490. };
  8491. reader.onloadend = function (e) {
  8492. request.onCompleteObservable.notifyObservers(request);
  8493. };
  8494. reader.onload = function (e) {
  8495. //target doesn't have result from ts 1.3
  8496. callback(e.target['result']);
  8497. };
  8498. reader.onprogress = progressCallback;
  8499. reader.readAsDataURL(fileToLoad);
  8500. return request;
  8501. };
  8502. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  8503. var reader = new FileReader();
  8504. var request = {
  8505. onCompleteObservable: new BABYLON.Observable(),
  8506. abort: function () { return reader.abort(); },
  8507. };
  8508. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  8509. reader.onerror = function (e) {
  8510. Tools.Log("Error while reading file: " + fileToLoad.name);
  8511. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  8512. };
  8513. reader.onload = function (e) {
  8514. //target doesn't have result from ts 1.3
  8515. callback(e.target['result']);
  8516. };
  8517. if (progressCallBack) {
  8518. reader.onprogress = progressCallBack;
  8519. }
  8520. if (!useArrayBuffer) {
  8521. // Asynchronous read
  8522. reader.readAsText(fileToLoad);
  8523. }
  8524. else {
  8525. reader.readAsArrayBuffer(fileToLoad);
  8526. }
  8527. return request;
  8528. };
  8529. //returns a downloadable url to a file content.
  8530. Tools.FileAsURL = function (content) {
  8531. var fileBlob = new Blob([content]);
  8532. var url = window.URL || window.webkitURL;
  8533. var link = url.createObjectURL(fileBlob);
  8534. return link;
  8535. };
  8536. // Misc.
  8537. Tools.Format = function (value, decimals) {
  8538. if (decimals === void 0) { decimals = 2; }
  8539. return value.toFixed(decimals);
  8540. };
  8541. Tools.CheckExtends = function (v, min, max) {
  8542. if (v.x < min.x)
  8543. min.x = v.x;
  8544. if (v.y < min.y)
  8545. min.y = v.y;
  8546. if (v.z < min.z)
  8547. min.z = v.z;
  8548. if (v.x > max.x)
  8549. max.x = v.x;
  8550. if (v.y > max.y)
  8551. max.y = v.y;
  8552. if (v.z > max.z)
  8553. max.z = v.z;
  8554. };
  8555. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  8556. for (var prop in source) {
  8557. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  8558. continue;
  8559. }
  8560. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  8561. continue;
  8562. }
  8563. var sourceValue = source[prop];
  8564. var typeOfSourceValue = typeof sourceValue;
  8565. if (typeOfSourceValue === "function") {
  8566. continue;
  8567. }
  8568. try {
  8569. if (typeOfSourceValue === "object") {
  8570. if (sourceValue instanceof Array) {
  8571. destination[prop] = [];
  8572. if (sourceValue.length > 0) {
  8573. if (typeof sourceValue[0] == "object") {
  8574. for (var index = 0; index < sourceValue.length; index++) {
  8575. var clonedValue = cloneValue(sourceValue[index], destination);
  8576. if (destination[prop].indexOf(clonedValue) === -1) {
  8577. destination[prop].push(clonedValue);
  8578. }
  8579. }
  8580. }
  8581. else {
  8582. destination[prop] = sourceValue.slice(0);
  8583. }
  8584. }
  8585. }
  8586. else {
  8587. destination[prop] = cloneValue(sourceValue, destination);
  8588. }
  8589. }
  8590. else {
  8591. destination[prop] = sourceValue;
  8592. }
  8593. }
  8594. catch (e) {
  8595. // Just ignore error (it could be because of a read-only property)
  8596. }
  8597. }
  8598. };
  8599. Tools.IsEmpty = function (obj) {
  8600. for (var i in obj) {
  8601. if (obj.hasOwnProperty(i)) {
  8602. return false;
  8603. }
  8604. }
  8605. return true;
  8606. };
  8607. Tools.RegisterTopRootEvents = function (events) {
  8608. for (var index = 0; index < events.length; index++) {
  8609. var event = events[index];
  8610. window.addEventListener(event.name, event.handler, false);
  8611. try {
  8612. if (window.parent) {
  8613. window.parent.addEventListener(event.name, event.handler, false);
  8614. }
  8615. }
  8616. catch (e) {
  8617. // Silently fails...
  8618. }
  8619. }
  8620. };
  8621. Tools.UnregisterTopRootEvents = function (events) {
  8622. for (var index = 0; index < events.length; index++) {
  8623. var event = events[index];
  8624. window.removeEventListener(event.name, event.handler);
  8625. try {
  8626. if (window.parent) {
  8627. window.parent.removeEventListener(event.name, event.handler);
  8628. }
  8629. }
  8630. catch (e) {
  8631. // Silently fails...
  8632. }
  8633. }
  8634. };
  8635. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  8636. if (mimeType === void 0) { mimeType = "image/png"; }
  8637. // Read the contents of the framebuffer
  8638. var numberOfChannelsByLine = width * 4;
  8639. var halfHeight = height / 2;
  8640. //Reading datas from WebGL
  8641. var data = engine.readPixels(0, 0, width, height);
  8642. //To flip image on Y axis.
  8643. for (var i = 0; i < halfHeight; i++) {
  8644. for (var j = 0; j < numberOfChannelsByLine; j++) {
  8645. var currentCell = j + i * numberOfChannelsByLine;
  8646. var targetLine = height - i - 1;
  8647. var targetCell = j + targetLine * numberOfChannelsByLine;
  8648. var temp = data[currentCell];
  8649. data[currentCell] = data[targetCell];
  8650. data[targetCell] = temp;
  8651. }
  8652. }
  8653. // Create a 2D canvas to store the result
  8654. if (!screenshotCanvas) {
  8655. screenshotCanvas = document.createElement('canvas');
  8656. }
  8657. screenshotCanvas.width = width;
  8658. screenshotCanvas.height = height;
  8659. var context = screenshotCanvas.getContext('2d');
  8660. if (context) {
  8661. // Copy the pixels to a 2D canvas
  8662. var imageData = context.createImageData(width, height);
  8663. var castData = (imageData.data);
  8664. castData.set(data);
  8665. context.putImageData(imageData, 0, 0);
  8666. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  8667. }
  8668. };
  8669. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  8670. if (mimeType === void 0) { mimeType = "image/png"; }
  8671. var base64Image = screenshotCanvas.toDataURL(mimeType);
  8672. if (successCallback) {
  8673. successCallback(base64Image);
  8674. }
  8675. else {
  8676. // We need HTMLCanvasElement.toBlob for HD screenshots
  8677. if (!screenshotCanvas.toBlob) {
  8678. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  8679. screenshotCanvas.toBlob = function (callback, type, quality) {
  8680. var _this = this;
  8681. setTimeout(function () {
  8682. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  8683. for (var i = 0; i < len; i++) {
  8684. arr[i] = binStr.charCodeAt(i);
  8685. }
  8686. callback(new Blob([arr], { type: type || 'image/png' }));
  8687. });
  8688. };
  8689. }
  8690. screenshotCanvas.toBlob(function (blob) {
  8691. var url = URL.createObjectURL(blob);
  8692. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  8693. if (("download" in document.createElement("a"))) {
  8694. var a = window.document.createElement("a");
  8695. a.href = url;
  8696. if (fileName) {
  8697. a.setAttribute("download", fileName);
  8698. }
  8699. else {
  8700. var date = new Date();
  8701. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  8702. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  8703. }
  8704. window.document.body.appendChild(a);
  8705. a.addEventListener("click", function () {
  8706. if (a.parentElement) {
  8707. a.parentElement.removeChild(a);
  8708. }
  8709. });
  8710. a.click();
  8711. }
  8712. else {
  8713. var newWindow = window.open("");
  8714. if (!newWindow)
  8715. return;
  8716. var img = newWindow.document.createElement("img");
  8717. img.onload = function () {
  8718. // no longer need to read the blob so it's revoked
  8719. URL.revokeObjectURL(url);
  8720. };
  8721. img.src = url;
  8722. newWindow.document.body.appendChild(img);
  8723. }
  8724. });
  8725. }
  8726. };
  8727. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  8728. if (mimeType === void 0) { mimeType = "image/png"; }
  8729. var width;
  8730. var height;
  8731. // If a precision value is specified
  8732. if (size.precision) {
  8733. width = Math.round(engine.getRenderWidth() * size.precision);
  8734. height = Math.round(width / engine.getAspectRatio(camera));
  8735. }
  8736. else if (size.width && size.height) {
  8737. width = size.width;
  8738. height = size.height;
  8739. }
  8740. else if (size.width && !size.height) {
  8741. width = size.width;
  8742. height = Math.round(width / engine.getAspectRatio(camera));
  8743. }
  8744. else if (size.height && !size.width) {
  8745. height = size.height;
  8746. width = Math.round(height * engine.getAspectRatio(camera));
  8747. }
  8748. else if (!isNaN(size)) {
  8749. height = size;
  8750. width = size;
  8751. }
  8752. else {
  8753. Tools.Error("Invalid 'size' parameter !");
  8754. return;
  8755. }
  8756. if (!screenshotCanvas) {
  8757. screenshotCanvas = document.createElement('canvas');
  8758. }
  8759. screenshotCanvas.width = width;
  8760. screenshotCanvas.height = height;
  8761. var renderContext = screenshotCanvas.getContext("2d");
  8762. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  8763. var newWidth = width;
  8764. var newHeight = newWidth / ratio;
  8765. if (newHeight > height) {
  8766. newHeight = height;
  8767. newWidth = newHeight * ratio;
  8768. }
  8769. var offsetX = Math.max(0, width - newWidth) / 2;
  8770. var offsetY = Math.max(0, height - newHeight) / 2;
  8771. var renderingCanvas = engine.getRenderingCanvas();
  8772. if (renderContext && renderingCanvas) {
  8773. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  8774. }
  8775. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  8776. };
  8777. /**
  8778. * Generates an image screenshot from the specified camera.
  8779. *
  8780. * @param engine The engine to use for rendering
  8781. * @param camera The camera to use for rendering
  8782. * @param size This parameter can be set to a single number or to an object with the
  8783. * following (optional) properties: precision, width, height. If a single number is passed,
  8784. * it will be used for both width and height. If an object is passed, the screenshot size
  8785. * will be derived from the parameters. The precision property is a multiplier allowing
  8786. * rendering at a higher or lower resolution.
  8787. * @param successCallback The callback receives a single parameter which contains the
  8788. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  8789. * src parameter of an <img> to display it.
  8790. * @param mimeType The MIME type of the screenshot image (default: image/png).
  8791. * Check your browser for supported MIME types.
  8792. * @param samples Texture samples (default: 1)
  8793. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  8794. * @param fileName A name for for the downloaded file.
  8795. * @constructor
  8796. */
  8797. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  8798. if (mimeType === void 0) { mimeType = "image/png"; }
  8799. if (samples === void 0) { samples = 1; }
  8800. if (antialiasing === void 0) { antialiasing = false; }
  8801. var width;
  8802. var height;
  8803. //If a precision value is specified
  8804. if (size.precision) {
  8805. width = Math.round(engine.getRenderWidth() * size.precision);
  8806. height = Math.round(width / engine.getAspectRatio(camera));
  8807. size = { width: width, height: height };
  8808. }
  8809. else if (size.width && size.height) {
  8810. width = size.width;
  8811. height = size.height;
  8812. }
  8813. else if (size.width && !size.height) {
  8814. width = size.width;
  8815. height = Math.round(width / engine.getAspectRatio(camera));
  8816. size = { width: width, height: height };
  8817. }
  8818. else if (size.height && !size.width) {
  8819. height = size.height;
  8820. width = Math.round(height * engine.getAspectRatio(camera));
  8821. size = { width: width, height: height };
  8822. }
  8823. else if (!isNaN(size)) {
  8824. height = size;
  8825. width = size;
  8826. }
  8827. else {
  8828. Tools.Error("Invalid 'size' parameter !");
  8829. return;
  8830. }
  8831. var scene = camera.getScene();
  8832. var previousCamera = null;
  8833. if (scene.activeCamera !== camera) {
  8834. previousCamera = scene.activeCamera;
  8835. scene.activeCamera = camera;
  8836. }
  8837. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  8838. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8839. texture.renderList = null;
  8840. texture.samples = samples;
  8841. if (antialiasing) {
  8842. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  8843. }
  8844. texture.onAfterRenderObservable.add(function () {
  8845. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  8846. });
  8847. scene.incrementRenderId();
  8848. scene.resetCachedMaterial();
  8849. texture.render(true);
  8850. texture.dispose();
  8851. if (previousCamera) {
  8852. scene.activeCamera = previousCamera;
  8853. }
  8854. camera.getProjectionMatrix(true); // Force cache refresh;
  8855. };
  8856. // XHR response validator for local file scenario
  8857. Tools.ValidateXHRData = function (xhr, dataType) {
  8858. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  8859. if (dataType === void 0) { dataType = 7; }
  8860. try {
  8861. if (dataType & 1) {
  8862. if (xhr.responseText && xhr.responseText.length > 0) {
  8863. return true;
  8864. }
  8865. else if (dataType === 1) {
  8866. return false;
  8867. }
  8868. }
  8869. if (dataType & 2) {
  8870. // Check header width and height since there is no "TGA" magic number
  8871. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  8872. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  8873. return true;
  8874. }
  8875. else if (dataType === 2) {
  8876. return false;
  8877. }
  8878. }
  8879. if (dataType & 4) {
  8880. // Check for the "DDS" magic number
  8881. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  8882. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  8883. return true;
  8884. }
  8885. else {
  8886. return false;
  8887. }
  8888. }
  8889. }
  8890. catch (e) {
  8891. // Global protection
  8892. }
  8893. return false;
  8894. };
  8895. /**
  8896. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  8897. * Be aware Math.random() could cause collisions, but:
  8898. * "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"
  8899. */
  8900. Tools.RandomId = function () {
  8901. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  8902. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  8903. return v.toString(16);
  8904. });
  8905. };
  8906. /**
  8907. * Test if the given uri is a base64 string.
  8908. * @param uri The uri to test
  8909. * @return True if the uri is a base64 string or false otherwise.
  8910. */
  8911. Tools.IsBase64 = function (uri) {
  8912. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  8913. };
  8914. /**
  8915. * Decode the given base64 uri.
  8916. * @param uri The uri to decode
  8917. * @return The decoded base64 data.
  8918. */
  8919. Tools.DecodeBase64 = function (uri) {
  8920. var decodedString = atob(uri.split(",")[1]);
  8921. var bufferLength = decodedString.length;
  8922. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  8923. for (var i = 0; i < bufferLength; i++) {
  8924. bufferView[i] = decodedString.charCodeAt(i);
  8925. }
  8926. return bufferView.buffer;
  8927. };
  8928. Object.defineProperty(Tools, "NoneLogLevel", {
  8929. get: function () {
  8930. return Tools._NoneLogLevel;
  8931. },
  8932. enumerable: true,
  8933. configurable: true
  8934. });
  8935. Object.defineProperty(Tools, "MessageLogLevel", {
  8936. get: function () {
  8937. return Tools._MessageLogLevel;
  8938. },
  8939. enumerable: true,
  8940. configurable: true
  8941. });
  8942. Object.defineProperty(Tools, "WarningLogLevel", {
  8943. get: function () {
  8944. return Tools._WarningLogLevel;
  8945. },
  8946. enumerable: true,
  8947. configurable: true
  8948. });
  8949. Object.defineProperty(Tools, "ErrorLogLevel", {
  8950. get: function () {
  8951. return Tools._ErrorLogLevel;
  8952. },
  8953. enumerable: true,
  8954. configurable: true
  8955. });
  8956. Object.defineProperty(Tools, "AllLogLevel", {
  8957. get: function () {
  8958. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  8959. },
  8960. enumerable: true,
  8961. configurable: true
  8962. });
  8963. Tools._AddLogEntry = function (entry) {
  8964. Tools._LogCache = entry + Tools._LogCache;
  8965. if (Tools.OnNewCacheEntry) {
  8966. Tools.OnNewCacheEntry(entry);
  8967. }
  8968. };
  8969. Tools._FormatMessage = function (message) {
  8970. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  8971. var date = new Date();
  8972. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  8973. };
  8974. Tools._LogDisabled = function (message) {
  8975. // nothing to do
  8976. };
  8977. Tools._LogEnabled = function (message) {
  8978. var formattedMessage = Tools._FormatMessage(message);
  8979. console.log("BJS - " + formattedMessage);
  8980. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  8981. Tools._AddLogEntry(entry);
  8982. };
  8983. Tools._WarnDisabled = function (message) {
  8984. // nothing to do
  8985. };
  8986. Tools._WarnEnabled = function (message) {
  8987. var formattedMessage = Tools._FormatMessage(message);
  8988. console.warn("BJS - " + formattedMessage);
  8989. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  8990. Tools._AddLogEntry(entry);
  8991. };
  8992. Tools._ErrorDisabled = function (message) {
  8993. // nothing to do
  8994. };
  8995. Tools._ErrorEnabled = function (message) {
  8996. Tools.errorsCount++;
  8997. var formattedMessage = Tools._FormatMessage(message);
  8998. console.error("BJS - " + formattedMessage);
  8999. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9000. Tools._AddLogEntry(entry);
  9001. };
  9002. Object.defineProperty(Tools, "LogCache", {
  9003. get: function () {
  9004. return Tools._LogCache;
  9005. },
  9006. enumerable: true,
  9007. configurable: true
  9008. });
  9009. Tools.ClearLogCache = function () {
  9010. Tools._LogCache = "";
  9011. Tools.errorsCount = 0;
  9012. };
  9013. Object.defineProperty(Tools, "LogLevels", {
  9014. set: function (level) {
  9015. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9016. Tools.Log = Tools._LogEnabled;
  9017. }
  9018. else {
  9019. Tools.Log = Tools._LogDisabled;
  9020. }
  9021. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9022. Tools.Warn = Tools._WarnEnabled;
  9023. }
  9024. else {
  9025. Tools.Warn = Tools._WarnDisabled;
  9026. }
  9027. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9028. Tools.Error = Tools._ErrorEnabled;
  9029. }
  9030. else {
  9031. Tools.Error = Tools._ErrorDisabled;
  9032. }
  9033. },
  9034. enumerable: true,
  9035. configurable: true
  9036. });
  9037. Tools.IsWindowObjectExist = function () {
  9038. return (typeof window) !== "undefined";
  9039. };
  9040. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9041. get: function () {
  9042. return Tools._PerformanceNoneLogLevel;
  9043. },
  9044. enumerable: true,
  9045. configurable: true
  9046. });
  9047. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9048. get: function () {
  9049. return Tools._PerformanceUserMarkLogLevel;
  9050. },
  9051. enumerable: true,
  9052. configurable: true
  9053. });
  9054. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9055. get: function () {
  9056. return Tools._PerformanceConsoleLogLevel;
  9057. },
  9058. enumerable: true,
  9059. configurable: true
  9060. });
  9061. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9062. set: function (level) {
  9063. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9064. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9065. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9066. return;
  9067. }
  9068. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9069. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9070. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9071. return;
  9072. }
  9073. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9074. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9075. },
  9076. enumerable: true,
  9077. configurable: true
  9078. });
  9079. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9080. };
  9081. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9082. };
  9083. Tools._StartUserMark = function (counterName, condition) {
  9084. if (condition === void 0) { condition = true; }
  9085. if (!Tools._performance) {
  9086. if (!Tools.IsWindowObjectExist()) {
  9087. return;
  9088. }
  9089. Tools._performance = window.performance;
  9090. }
  9091. if (!condition || !Tools._performance.mark) {
  9092. return;
  9093. }
  9094. Tools._performance.mark(counterName + "-Begin");
  9095. };
  9096. Tools._EndUserMark = function (counterName, condition) {
  9097. if (condition === void 0) { condition = true; }
  9098. if (!condition || !Tools._performance.mark) {
  9099. return;
  9100. }
  9101. Tools._performance.mark(counterName + "-End");
  9102. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9103. };
  9104. Tools._StartPerformanceConsole = function (counterName, condition) {
  9105. if (condition === void 0) { condition = true; }
  9106. if (!condition) {
  9107. return;
  9108. }
  9109. Tools._StartUserMark(counterName, condition);
  9110. if (console.time) {
  9111. console.time(counterName);
  9112. }
  9113. };
  9114. Tools._EndPerformanceConsole = function (counterName, condition) {
  9115. if (condition === void 0) { condition = true; }
  9116. if (!condition) {
  9117. return;
  9118. }
  9119. Tools._EndUserMark(counterName, condition);
  9120. if (console.time) {
  9121. console.timeEnd(counterName);
  9122. }
  9123. };
  9124. Object.defineProperty(Tools, "Now", {
  9125. get: function () {
  9126. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9127. return window.performance.now();
  9128. }
  9129. return new Date().getTime();
  9130. },
  9131. enumerable: true,
  9132. configurable: true
  9133. });
  9134. /**
  9135. * This method will return the name of the class used to create the instance of the given object.
  9136. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9137. * @param object the object to get the class name from
  9138. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9139. */
  9140. Tools.GetClassName = function (object, isType) {
  9141. if (isType === void 0) { isType = false; }
  9142. var name = null;
  9143. if (!isType && object.getClassName) {
  9144. name = object.getClassName();
  9145. }
  9146. else {
  9147. if (object instanceof Object) {
  9148. var classObj = isType ? object : Object.getPrototypeOf(object);
  9149. name = classObj.constructor["__bjsclassName__"];
  9150. }
  9151. if (!name) {
  9152. name = typeof object;
  9153. }
  9154. }
  9155. return name;
  9156. };
  9157. Tools.First = function (array, predicate) {
  9158. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9159. var el = array_1[_i];
  9160. if (predicate(el)) {
  9161. return el;
  9162. }
  9163. }
  9164. return null;
  9165. };
  9166. /**
  9167. * This method will return the name of the full name of the class, including its owning module (if any).
  9168. * 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).
  9169. * @param object the object to get the class name from
  9170. * @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.
  9171. */
  9172. Tools.getFullClassName = function (object, isType) {
  9173. if (isType === void 0) { isType = false; }
  9174. var className = null;
  9175. var moduleName = null;
  9176. if (!isType && object.getClassName) {
  9177. className = object.getClassName();
  9178. }
  9179. else {
  9180. if (object instanceof Object) {
  9181. var classObj = isType ? object : Object.getPrototypeOf(object);
  9182. className = classObj.constructor["__bjsclassName__"];
  9183. moduleName = classObj.constructor["__bjsmoduleName__"];
  9184. }
  9185. if (!className) {
  9186. className = typeof object;
  9187. }
  9188. }
  9189. if (!className) {
  9190. return null;
  9191. }
  9192. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9193. };
  9194. /**
  9195. * 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.
  9196. * @param array
  9197. */
  9198. Tools.arrayOrStringFeeder = function (array) {
  9199. return function (index) {
  9200. if (index >= array.length) {
  9201. return null;
  9202. }
  9203. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9204. if (val && val.getHashCode) {
  9205. val = val.getHashCode();
  9206. }
  9207. if (typeof val === "string") {
  9208. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9209. }
  9210. return val;
  9211. };
  9212. };
  9213. /**
  9214. * Compute the hashCode of a stream of number
  9215. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9216. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9217. * @return the hash code computed
  9218. */
  9219. Tools.hashCodeFromStream = function (feeder) {
  9220. // Based from here: http://stackoverflow.com/a/7616484/802124
  9221. var hash = 0;
  9222. var index = 0;
  9223. var chr = feeder(index++);
  9224. while (chr != null) {
  9225. hash = ((hash << 5) - hash) + chr;
  9226. hash |= 0; // Convert to 32bit integer
  9227. chr = feeder(index++);
  9228. }
  9229. return hash;
  9230. };
  9231. /**
  9232. * Returns a promise that resolves after the given amount of time.
  9233. * @param delay Number of milliseconds to delay
  9234. * @returns Promise that resolves after the given amount of time
  9235. */
  9236. Tools.DelayAsync = function (delay) {
  9237. return new Promise(function (resolve) {
  9238. setTimeout(function () {
  9239. resolve();
  9240. }, delay);
  9241. });
  9242. };
  9243. Tools.BaseUrl = "";
  9244. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9245. /**
  9246. * Default behaviour for cors in the application.
  9247. * It can be a string if the expected behavior is identical in the entire app.
  9248. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9249. */
  9250. Tools.CorsBehavior = "anonymous";
  9251. Tools.UseFallbackTexture = true;
  9252. /**
  9253. * Use this object to register external classes like custom textures or material
  9254. * to allow the laoders to instantiate them
  9255. */
  9256. Tools.RegisteredExternalClasses = {};
  9257. // Used in case of a texture loading problem
  9258. 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";
  9259. Tools.PreprocessUrl = function (url) {
  9260. return url;
  9261. };
  9262. // Logs
  9263. Tools._NoneLogLevel = 0;
  9264. Tools._MessageLogLevel = 1;
  9265. Tools._WarningLogLevel = 2;
  9266. Tools._ErrorLogLevel = 4;
  9267. Tools._LogCache = "";
  9268. Tools.errorsCount = 0;
  9269. Tools.Log = Tools._LogEnabled;
  9270. Tools.Warn = Tools._WarnEnabled;
  9271. Tools.Error = Tools._ErrorEnabled;
  9272. // Performances
  9273. Tools._PerformanceNoneLogLevel = 0;
  9274. Tools._PerformanceUserMarkLogLevel = 1;
  9275. Tools._PerformanceConsoleLogLevel = 2;
  9276. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9277. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9278. return Tools;
  9279. }());
  9280. BABYLON.Tools = Tools;
  9281. /**
  9282. * This class is used to track a performance counter which is number based.
  9283. * The user has access to many properties which give statistics of different nature
  9284. *
  9285. * The implementer can track two kinds of Performance Counter: time and count
  9286. * 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.
  9287. * 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.
  9288. */
  9289. var PerfCounter = /** @class */ (function () {
  9290. function PerfCounter() {
  9291. this._startMonitoringTime = 0;
  9292. this._min = 0;
  9293. this._max = 0;
  9294. this._average = 0;
  9295. this._lastSecAverage = 0;
  9296. this._current = 0;
  9297. this._totalValueCount = 0;
  9298. this._totalAccumulated = 0;
  9299. this._lastSecAccumulated = 0;
  9300. this._lastSecTime = 0;
  9301. this._lastSecValueCount = 0;
  9302. }
  9303. Object.defineProperty(PerfCounter.prototype, "min", {
  9304. /**
  9305. * Returns the smallest value ever
  9306. */
  9307. get: function () {
  9308. return this._min;
  9309. },
  9310. enumerable: true,
  9311. configurable: true
  9312. });
  9313. Object.defineProperty(PerfCounter.prototype, "max", {
  9314. /**
  9315. * Returns the biggest value ever
  9316. */
  9317. get: function () {
  9318. return this._max;
  9319. },
  9320. enumerable: true,
  9321. configurable: true
  9322. });
  9323. Object.defineProperty(PerfCounter.prototype, "average", {
  9324. /**
  9325. * Returns the average value since the performance counter is running
  9326. */
  9327. get: function () {
  9328. return this._average;
  9329. },
  9330. enumerable: true,
  9331. configurable: true
  9332. });
  9333. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9334. /**
  9335. * Returns the average value of the last second the counter was monitored
  9336. */
  9337. get: function () {
  9338. return this._lastSecAverage;
  9339. },
  9340. enumerable: true,
  9341. configurable: true
  9342. });
  9343. Object.defineProperty(PerfCounter.prototype, "current", {
  9344. /**
  9345. * Returns the current value
  9346. */
  9347. get: function () {
  9348. return this._current;
  9349. },
  9350. enumerable: true,
  9351. configurable: true
  9352. });
  9353. Object.defineProperty(PerfCounter.prototype, "total", {
  9354. get: function () {
  9355. return this._totalAccumulated;
  9356. },
  9357. enumerable: true,
  9358. configurable: true
  9359. });
  9360. Object.defineProperty(PerfCounter.prototype, "count", {
  9361. get: function () {
  9362. return this._totalValueCount;
  9363. },
  9364. enumerable: true,
  9365. configurable: true
  9366. });
  9367. /**
  9368. * Call this method to start monitoring a new frame.
  9369. * 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.
  9370. */
  9371. PerfCounter.prototype.fetchNewFrame = function () {
  9372. this._totalValueCount++;
  9373. this._current = 0;
  9374. this._lastSecValueCount++;
  9375. };
  9376. /**
  9377. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9378. * @param newCount the count value to add to the monitored count
  9379. * @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.
  9380. */
  9381. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9382. if (!PerfCounter.Enabled) {
  9383. return;
  9384. }
  9385. this._current += newCount;
  9386. if (fetchResult) {
  9387. this._fetchResult();
  9388. }
  9389. };
  9390. /**
  9391. * Start monitoring this performance counter
  9392. */
  9393. PerfCounter.prototype.beginMonitoring = function () {
  9394. if (!PerfCounter.Enabled) {
  9395. return;
  9396. }
  9397. this._startMonitoringTime = Tools.Now;
  9398. };
  9399. /**
  9400. * Compute the time lapsed since the previous beginMonitoring() call.
  9401. * @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
  9402. */
  9403. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9404. if (newFrame === void 0) { newFrame = true; }
  9405. if (!PerfCounter.Enabled) {
  9406. return;
  9407. }
  9408. if (newFrame) {
  9409. this.fetchNewFrame();
  9410. }
  9411. var currentTime = Tools.Now;
  9412. this._current = currentTime - this._startMonitoringTime;
  9413. if (newFrame) {
  9414. this._fetchResult();
  9415. }
  9416. };
  9417. PerfCounter.prototype._fetchResult = function () {
  9418. this._totalAccumulated += this._current;
  9419. this._lastSecAccumulated += this._current;
  9420. // Min/Max update
  9421. this._min = Math.min(this._min, this._current);
  9422. this._max = Math.max(this._max, this._current);
  9423. this._average = this._totalAccumulated / this._totalValueCount;
  9424. // Reset last sec?
  9425. var now = Tools.Now;
  9426. if ((now - this._lastSecTime) > 1000) {
  9427. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9428. this._lastSecTime = now;
  9429. this._lastSecAccumulated = 0;
  9430. this._lastSecValueCount = 0;
  9431. }
  9432. };
  9433. PerfCounter.Enabled = true;
  9434. return PerfCounter;
  9435. }());
  9436. BABYLON.PerfCounter = PerfCounter;
  9437. /**
  9438. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9439. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9440. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9441. * @param name The name of the class, case should be preserved
  9442. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9443. */
  9444. function className(name, module) {
  9445. return function (target) {
  9446. target["__bjsclassName__"] = name;
  9447. target["__bjsmoduleName__"] = (module != null) ? module : null;
  9448. };
  9449. }
  9450. BABYLON.className = className;
  9451. /**
  9452. * An implementation of a loop for asynchronous functions.
  9453. */
  9454. var AsyncLoop = /** @class */ (function () {
  9455. /**
  9456. * Constroctor.
  9457. * @param iterations the number of iterations.
  9458. * @param _fn the function to run each iteration
  9459. * @param _successCallback the callback that will be called upon succesful execution
  9460. * @param offset starting offset.
  9461. */
  9462. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  9463. if (offset === void 0) { offset = 0; }
  9464. this.iterations = iterations;
  9465. this._fn = _fn;
  9466. this._successCallback = _successCallback;
  9467. this.index = offset - 1;
  9468. this._done = false;
  9469. }
  9470. /**
  9471. * Execute the next iteration. Must be called after the last iteration was finished.
  9472. */
  9473. AsyncLoop.prototype.executeNext = function () {
  9474. if (!this._done) {
  9475. if (this.index + 1 < this.iterations) {
  9476. ++this.index;
  9477. this._fn(this);
  9478. }
  9479. else {
  9480. this.breakLoop();
  9481. }
  9482. }
  9483. };
  9484. /**
  9485. * Break the loop and run the success callback.
  9486. */
  9487. AsyncLoop.prototype.breakLoop = function () {
  9488. this._done = true;
  9489. this._successCallback();
  9490. };
  9491. /**
  9492. * Helper function
  9493. */
  9494. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  9495. if (offset === void 0) { offset = 0; }
  9496. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  9497. loop.executeNext();
  9498. return loop;
  9499. };
  9500. /**
  9501. * A for-loop that will run a given number of iterations synchronous and the rest async.
  9502. * @param iterations total number of iterations
  9503. * @param syncedIterations number of synchronous iterations in each async iteration.
  9504. * @param fn the function to call each iteration.
  9505. * @param callback a success call back that will be called when iterating stops.
  9506. * @param breakFunction a break condition (optional)
  9507. * @param timeout timeout settings for the setTimeout function. default - 0.
  9508. * @constructor
  9509. */
  9510. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  9511. if (timeout === void 0) { timeout = 0; }
  9512. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  9513. if (breakFunction && breakFunction())
  9514. loop.breakLoop();
  9515. else {
  9516. setTimeout(function () {
  9517. for (var i = 0; i < syncedIterations; ++i) {
  9518. var iteration = (loop.index * syncedIterations) + i;
  9519. if (iteration >= iterations)
  9520. break;
  9521. fn(iteration);
  9522. if (breakFunction && breakFunction()) {
  9523. loop.breakLoop();
  9524. break;
  9525. }
  9526. }
  9527. loop.executeNext();
  9528. }, timeout);
  9529. }
  9530. }, callback);
  9531. };
  9532. return AsyncLoop;
  9533. }());
  9534. BABYLON.AsyncLoop = AsyncLoop;
  9535. })(BABYLON || (BABYLON = {}));
  9536. //# sourceMappingURL=babylon.tools.js.map
  9537. "use strict";
  9538. var BABYLON;
  9539. (function (BABYLON) {
  9540. var PromiseStates;
  9541. (function (PromiseStates) {
  9542. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  9543. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  9544. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  9545. })(PromiseStates || (PromiseStates = {}));
  9546. var FulFillmentAgregator = /** @class */ (function () {
  9547. function FulFillmentAgregator() {
  9548. this.count = 0;
  9549. this.target = 0;
  9550. this.results = [];
  9551. }
  9552. return FulFillmentAgregator;
  9553. }());
  9554. var InternalPromise = /** @class */ (function () {
  9555. function InternalPromise(resolver) {
  9556. var _this = this;
  9557. this._state = PromiseStates.Pending;
  9558. this._children = new Array();
  9559. this._rejectWasConsumed = false;
  9560. if (!resolver) {
  9561. return;
  9562. }
  9563. try {
  9564. resolver(function (value) {
  9565. _this._resolve(value);
  9566. }, function (reason) {
  9567. _this._reject(reason);
  9568. });
  9569. }
  9570. catch (e) {
  9571. this._reject(e);
  9572. }
  9573. }
  9574. InternalPromise.prototype.catch = function (onRejected) {
  9575. return this.then(undefined, onRejected);
  9576. };
  9577. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  9578. var _this = this;
  9579. var newPromise = new InternalPromise();
  9580. newPromise._onFulfilled = onFulfilled;
  9581. newPromise._onRejected = onRejected;
  9582. // Composition
  9583. this._children.push(newPromise);
  9584. if (this._state !== PromiseStates.Pending) {
  9585. BABYLON.Tools.SetImmediate(function () {
  9586. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  9587. var returnedValue = newPromise._resolve(_this._result);
  9588. if (returnedValue !== undefined && returnedValue !== null) {
  9589. if (returnedValue._state !== undefined) {
  9590. var returnedPromise = returnedValue;
  9591. newPromise._children.push(returnedPromise);
  9592. newPromise = returnedPromise;
  9593. }
  9594. else {
  9595. newPromise._result = returnedValue;
  9596. }
  9597. }
  9598. }
  9599. else {
  9600. newPromise._reject(_this._reason);
  9601. }
  9602. });
  9603. }
  9604. return newPromise;
  9605. };
  9606. InternalPromise.prototype._moveChildren = function (children) {
  9607. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  9608. if (this._state === PromiseStates.Fulfilled) {
  9609. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  9610. var child = _b[_i];
  9611. child._resolve(this._result);
  9612. }
  9613. }
  9614. else if (this._state === PromiseStates.Rejected) {
  9615. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  9616. var child = _d[_c];
  9617. child._reject(this._reason);
  9618. }
  9619. }
  9620. var _a;
  9621. };
  9622. InternalPromise.prototype._resolve = function (value) {
  9623. try {
  9624. this._state = PromiseStates.Fulfilled;
  9625. this._result = value;
  9626. var returnedValue = null;
  9627. if (this._onFulfilled) {
  9628. returnedValue = this._onFulfilled(value);
  9629. }
  9630. if (returnedValue !== undefined && returnedValue !== null) {
  9631. if (returnedValue._state !== undefined) {
  9632. // Transmit children
  9633. var returnedPromise = returnedValue;
  9634. returnedPromise._moveChildren(this._children);
  9635. }
  9636. else {
  9637. value = returnedValue;
  9638. }
  9639. }
  9640. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9641. var child = _a[_i];
  9642. child._resolve(value);
  9643. }
  9644. this._children.length = 0;
  9645. delete this._onFulfilled;
  9646. delete this._onRejected;
  9647. return returnedValue;
  9648. }
  9649. catch (e) {
  9650. this._reject(e, true);
  9651. }
  9652. return null;
  9653. };
  9654. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  9655. if (onLocalThrow === void 0) { onLocalThrow = false; }
  9656. this._state = PromiseStates.Rejected;
  9657. this._reason = reason;
  9658. if (this._onRejected && !onLocalThrow) {
  9659. try {
  9660. this._onRejected(reason);
  9661. this._rejectWasConsumed = true;
  9662. }
  9663. catch (e) {
  9664. reason = e;
  9665. }
  9666. }
  9667. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  9668. var child = _a[_i];
  9669. if (this._rejectWasConsumed) {
  9670. child._resolve(null);
  9671. }
  9672. else {
  9673. child._reject(reason);
  9674. }
  9675. }
  9676. this._children.length = 0;
  9677. delete this._onFulfilled;
  9678. delete this._onRejected;
  9679. };
  9680. InternalPromise.resolve = function (value) {
  9681. var newPromise = new InternalPromise();
  9682. newPromise._resolve(value);
  9683. return newPromise;
  9684. };
  9685. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  9686. promise.then(function (value) {
  9687. agregator.results[index] = value;
  9688. agregator.count++;
  9689. if (agregator.count === agregator.target) {
  9690. agregator.rootPromise._resolve(agregator.results);
  9691. }
  9692. return null;
  9693. }, function (reason) {
  9694. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  9695. agregator.rootPromise._reject(reason);
  9696. }
  9697. });
  9698. };
  9699. InternalPromise.all = function (promises) {
  9700. var newPromise = new InternalPromise();
  9701. var agregator = new FulFillmentAgregator();
  9702. agregator.target = promises.length;
  9703. agregator.rootPromise = newPromise;
  9704. if (promises.length) {
  9705. for (var index = 0; index < promises.length; index++) {
  9706. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  9707. }
  9708. }
  9709. else {
  9710. newPromise._resolve([]);
  9711. }
  9712. return newPromise;
  9713. };
  9714. InternalPromise.race = function (promises) {
  9715. var newPromise = new InternalPromise();
  9716. if (promises.length) {
  9717. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  9718. var promise = promises_1[_i];
  9719. promise.then(function (value) {
  9720. if (newPromise) {
  9721. newPromise._resolve(value);
  9722. newPromise = null;
  9723. }
  9724. return null;
  9725. }, function (reason) {
  9726. if (newPromise) {
  9727. newPromise._reject(reason);
  9728. newPromise = null;
  9729. }
  9730. });
  9731. }
  9732. }
  9733. return newPromise;
  9734. };
  9735. return InternalPromise;
  9736. }());
  9737. /**
  9738. * Helper class that provides a small promise polyfill
  9739. */
  9740. var PromisePolyfill = /** @class */ (function () {
  9741. function PromisePolyfill() {
  9742. }
  9743. /**
  9744. * Static function used to check if the polyfill is required
  9745. * If this is the case then the function will inject the polyfill to window.Promise
  9746. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  9747. */
  9748. PromisePolyfill.Apply = function (force) {
  9749. if (force === void 0) { force = false; }
  9750. if (force || typeof Promise === 'undefined') {
  9751. var root = window;
  9752. root.Promise = InternalPromise;
  9753. }
  9754. };
  9755. return PromisePolyfill;
  9756. }());
  9757. BABYLON.PromisePolyfill = PromisePolyfill;
  9758. })(BABYLON || (BABYLON = {}));
  9759. //# sourceMappingURL=babylon.promise.js.map
  9760. "use strict";
  9761. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  9762. var BABYLON;
  9763. (function (BABYLON) {
  9764. /**
  9765. * Helper class to push actions to a pool of workers.
  9766. */
  9767. var WorkerPool = /** @class */ (function () {
  9768. /**
  9769. * Constructor
  9770. * @param workers Array of workers to use for actions
  9771. */
  9772. function WorkerPool(workers) {
  9773. this._pendingActions = new Array();
  9774. this._workerInfos = workers.map(function (worker) { return ({
  9775. worker: worker,
  9776. active: false
  9777. }); });
  9778. }
  9779. /**
  9780. * Terminates all workers and clears any pending actions.
  9781. */
  9782. WorkerPool.prototype.dispose = function () {
  9783. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9784. var workerInfo = _a[_i];
  9785. workerInfo.worker.terminate();
  9786. }
  9787. delete this._workerInfos;
  9788. delete this._pendingActions;
  9789. };
  9790. /**
  9791. * Pushes an action to the worker pool. If all the workers are active, the action will be
  9792. * pended until a worker has completed its action.
  9793. * @param action The action to perform. Call onComplete when the action is complete.
  9794. */
  9795. WorkerPool.prototype.push = function (action) {
  9796. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  9797. var workerInfo = _a[_i];
  9798. if (!workerInfo.active) {
  9799. this._execute(workerInfo, action);
  9800. return;
  9801. }
  9802. }
  9803. this._pendingActions.push(action);
  9804. };
  9805. WorkerPool.prototype._execute = function (workerInfo, action) {
  9806. var _this = this;
  9807. workerInfo.active = true;
  9808. action(workerInfo.worker, function () {
  9809. workerInfo.active = false;
  9810. var nextAction = _this._pendingActions.shift();
  9811. if (nextAction) {
  9812. _this._execute(workerInfo, nextAction);
  9813. }
  9814. });
  9815. };
  9816. return WorkerPool;
  9817. }());
  9818. BABYLON.WorkerPool = WorkerPool;
  9819. })(BABYLON || (BABYLON = {}));
  9820. //# sourceMappingURL=babylon.workerPool.js.map
  9821. "use strict";
  9822. var BABYLON;
  9823. (function (BABYLON) {
  9824. var _AlphaState = /** @class */ (function () {
  9825. /**
  9826. * Initializes the state.
  9827. */
  9828. function _AlphaState() {
  9829. this._isAlphaBlendDirty = false;
  9830. this._isBlendFunctionParametersDirty = false;
  9831. this._isBlendEquationParametersDirty = false;
  9832. this._isBlendConstantsDirty = false;
  9833. this._alphaBlend = false;
  9834. this._blendFunctionParameters = new Array(4);
  9835. this._blendEquationParameters = new Array(2);
  9836. this._blendConstants = new Array(4);
  9837. this.reset();
  9838. }
  9839. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  9840. get: function () {
  9841. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  9842. },
  9843. enumerable: true,
  9844. configurable: true
  9845. });
  9846. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  9847. get: function () {
  9848. return this._alphaBlend;
  9849. },
  9850. set: function (value) {
  9851. if (this._alphaBlend === value) {
  9852. return;
  9853. }
  9854. this._alphaBlend = value;
  9855. this._isAlphaBlendDirty = true;
  9856. },
  9857. enumerable: true,
  9858. configurable: true
  9859. });
  9860. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  9861. if (this._blendConstants[0] === r &&
  9862. this._blendConstants[1] === g &&
  9863. this._blendConstants[2] === b &&
  9864. this._blendConstants[3] === a) {
  9865. return;
  9866. }
  9867. this._blendConstants[0] = r;
  9868. this._blendConstants[1] = g;
  9869. this._blendConstants[2] = b;
  9870. this._blendConstants[3] = a;
  9871. this._isBlendConstantsDirty = true;
  9872. };
  9873. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  9874. if (this._blendFunctionParameters[0] === value0 &&
  9875. this._blendFunctionParameters[1] === value1 &&
  9876. this._blendFunctionParameters[2] === value2 &&
  9877. this._blendFunctionParameters[3] === value3) {
  9878. return;
  9879. }
  9880. this._blendFunctionParameters[0] = value0;
  9881. this._blendFunctionParameters[1] = value1;
  9882. this._blendFunctionParameters[2] = value2;
  9883. this._blendFunctionParameters[3] = value3;
  9884. this._isBlendFunctionParametersDirty = true;
  9885. };
  9886. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  9887. if (this._blendEquationParameters[0] === rgb &&
  9888. this._blendEquationParameters[1] === alpha) {
  9889. return;
  9890. }
  9891. this._blendEquationParameters[0] = rgb;
  9892. this._blendEquationParameters[1] = alpha;
  9893. this._isBlendEquationParametersDirty = true;
  9894. };
  9895. _AlphaState.prototype.reset = function () {
  9896. this._alphaBlend = false;
  9897. this._blendFunctionParameters[0] = null;
  9898. this._blendFunctionParameters[1] = null;
  9899. this._blendFunctionParameters[2] = null;
  9900. this._blendFunctionParameters[3] = null;
  9901. this._blendEquationParameters[0] = null;
  9902. this._blendEquationParameters[1] = null;
  9903. this._blendConstants[0] = null;
  9904. this._blendConstants[1] = null;
  9905. this._blendConstants[2] = null;
  9906. this._blendConstants[3] = null;
  9907. this._isAlphaBlendDirty = true;
  9908. this._isBlendFunctionParametersDirty = false;
  9909. this._isBlendEquationParametersDirty = false;
  9910. this._isBlendConstantsDirty = false;
  9911. };
  9912. _AlphaState.prototype.apply = function (gl) {
  9913. if (!this.isDirty) {
  9914. return;
  9915. }
  9916. // Alpha blend
  9917. if (this._isAlphaBlendDirty) {
  9918. if (this._alphaBlend) {
  9919. gl.enable(gl.BLEND);
  9920. }
  9921. else {
  9922. gl.disable(gl.BLEND);
  9923. }
  9924. this._isAlphaBlendDirty = false;
  9925. }
  9926. // Alpha function
  9927. if (this._isBlendFunctionParametersDirty) {
  9928. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  9929. this._isBlendFunctionParametersDirty = false;
  9930. }
  9931. // Alpha equation
  9932. if (this._isBlendEquationParametersDirty) {
  9933. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  9934. this._isBlendEquationParametersDirty = false;
  9935. }
  9936. // Constants
  9937. if (this._isBlendConstantsDirty) {
  9938. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  9939. this._isBlendConstantsDirty = false;
  9940. }
  9941. };
  9942. return _AlphaState;
  9943. }());
  9944. BABYLON._AlphaState = _AlphaState;
  9945. })(BABYLON || (BABYLON = {}));
  9946. //# sourceMappingURL=babylon.alphaCullingState.js.map
  9947. "use strict";
  9948. var BABYLON;
  9949. (function (BABYLON) {
  9950. var _DepthCullingState = /** @class */ (function () {
  9951. /**
  9952. * Initializes the state.
  9953. */
  9954. function _DepthCullingState() {
  9955. this._isDepthTestDirty = false;
  9956. this._isDepthMaskDirty = false;
  9957. this._isDepthFuncDirty = false;
  9958. this._isCullFaceDirty = false;
  9959. this._isCullDirty = false;
  9960. this._isZOffsetDirty = false;
  9961. this._isFrontFaceDirty = false;
  9962. this.reset();
  9963. }
  9964. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  9965. get: function () {
  9966. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  9967. },
  9968. enumerable: true,
  9969. configurable: true
  9970. });
  9971. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  9972. get: function () {
  9973. return this._zOffset;
  9974. },
  9975. set: function (value) {
  9976. if (this._zOffset === value) {
  9977. return;
  9978. }
  9979. this._zOffset = value;
  9980. this._isZOffsetDirty = true;
  9981. },
  9982. enumerable: true,
  9983. configurable: true
  9984. });
  9985. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  9986. get: function () {
  9987. return this._cullFace;
  9988. },
  9989. set: function (value) {
  9990. if (this._cullFace === value) {
  9991. return;
  9992. }
  9993. this._cullFace = value;
  9994. this._isCullFaceDirty = true;
  9995. },
  9996. enumerable: true,
  9997. configurable: true
  9998. });
  9999. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10000. get: function () {
  10001. return this._cull;
  10002. },
  10003. set: function (value) {
  10004. if (this._cull === value) {
  10005. return;
  10006. }
  10007. this._cull = value;
  10008. this._isCullDirty = true;
  10009. },
  10010. enumerable: true,
  10011. configurable: true
  10012. });
  10013. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10014. get: function () {
  10015. return this._depthFunc;
  10016. },
  10017. set: function (value) {
  10018. if (this._depthFunc === value) {
  10019. return;
  10020. }
  10021. this._depthFunc = value;
  10022. this._isDepthFuncDirty = true;
  10023. },
  10024. enumerable: true,
  10025. configurable: true
  10026. });
  10027. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10028. get: function () {
  10029. return this._depthMask;
  10030. },
  10031. set: function (value) {
  10032. if (this._depthMask === value) {
  10033. return;
  10034. }
  10035. this._depthMask = value;
  10036. this._isDepthMaskDirty = true;
  10037. },
  10038. enumerable: true,
  10039. configurable: true
  10040. });
  10041. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10042. get: function () {
  10043. return this._depthTest;
  10044. },
  10045. set: function (value) {
  10046. if (this._depthTest === value) {
  10047. return;
  10048. }
  10049. this._depthTest = value;
  10050. this._isDepthTestDirty = true;
  10051. },
  10052. enumerable: true,
  10053. configurable: true
  10054. });
  10055. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10056. get: function () {
  10057. return this._frontFace;
  10058. },
  10059. set: function (value) {
  10060. if (this._frontFace === value) {
  10061. return;
  10062. }
  10063. this._frontFace = value;
  10064. this._isFrontFaceDirty = true;
  10065. },
  10066. enumerable: true,
  10067. configurable: true
  10068. });
  10069. _DepthCullingState.prototype.reset = function () {
  10070. this._depthMask = true;
  10071. this._depthTest = true;
  10072. this._depthFunc = null;
  10073. this._cullFace = null;
  10074. this._cull = null;
  10075. this._zOffset = 0;
  10076. this._frontFace = null;
  10077. this._isDepthTestDirty = true;
  10078. this._isDepthMaskDirty = true;
  10079. this._isDepthFuncDirty = false;
  10080. this._isCullFaceDirty = false;
  10081. this._isCullDirty = false;
  10082. this._isZOffsetDirty = false;
  10083. this._isFrontFaceDirty = false;
  10084. };
  10085. _DepthCullingState.prototype.apply = function (gl) {
  10086. if (!this.isDirty) {
  10087. return;
  10088. }
  10089. // Cull
  10090. if (this._isCullDirty) {
  10091. if (this.cull) {
  10092. gl.enable(gl.CULL_FACE);
  10093. }
  10094. else {
  10095. gl.disable(gl.CULL_FACE);
  10096. }
  10097. this._isCullDirty = false;
  10098. }
  10099. // Cull face
  10100. if (this._isCullFaceDirty) {
  10101. gl.cullFace(this.cullFace);
  10102. this._isCullFaceDirty = false;
  10103. }
  10104. // Depth mask
  10105. if (this._isDepthMaskDirty) {
  10106. gl.depthMask(this.depthMask);
  10107. this._isDepthMaskDirty = false;
  10108. }
  10109. // Depth test
  10110. if (this._isDepthTestDirty) {
  10111. if (this.depthTest) {
  10112. gl.enable(gl.DEPTH_TEST);
  10113. }
  10114. else {
  10115. gl.disable(gl.DEPTH_TEST);
  10116. }
  10117. this._isDepthTestDirty = false;
  10118. }
  10119. // Depth func
  10120. if (this._isDepthFuncDirty) {
  10121. gl.depthFunc(this.depthFunc);
  10122. this._isDepthFuncDirty = false;
  10123. }
  10124. // zOffset
  10125. if (this._isZOffsetDirty) {
  10126. if (this.zOffset) {
  10127. gl.enable(gl.POLYGON_OFFSET_FILL);
  10128. gl.polygonOffset(this.zOffset, 0);
  10129. }
  10130. else {
  10131. gl.disable(gl.POLYGON_OFFSET_FILL);
  10132. }
  10133. this._isZOffsetDirty = false;
  10134. }
  10135. // Front face
  10136. if (this._isFrontFaceDirty) {
  10137. gl.frontFace(this.frontFace);
  10138. this._isFrontFaceDirty = false;
  10139. }
  10140. };
  10141. return _DepthCullingState;
  10142. }());
  10143. BABYLON._DepthCullingState = _DepthCullingState;
  10144. })(BABYLON || (BABYLON = {}));
  10145. //# sourceMappingURL=babylon.depthCullingState.js.map
  10146. "use strict";
  10147. var BABYLON;
  10148. (function (BABYLON) {
  10149. var _StencilState = /** @class */ (function () {
  10150. function _StencilState() {
  10151. this._isStencilTestDirty = false;
  10152. this._isStencilMaskDirty = false;
  10153. this._isStencilFuncDirty = false;
  10154. this._isStencilOpDirty = false;
  10155. this.reset();
  10156. }
  10157. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10158. get: function () {
  10159. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10160. },
  10161. enumerable: true,
  10162. configurable: true
  10163. });
  10164. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10165. get: function () {
  10166. return this._stencilFunc;
  10167. },
  10168. set: function (value) {
  10169. if (this._stencilFunc === value) {
  10170. return;
  10171. }
  10172. this._stencilFunc = value;
  10173. this._isStencilFuncDirty = true;
  10174. },
  10175. enumerable: true,
  10176. configurable: true
  10177. });
  10178. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10179. get: function () {
  10180. return this._stencilFuncRef;
  10181. },
  10182. set: function (value) {
  10183. if (this._stencilFuncRef === value) {
  10184. return;
  10185. }
  10186. this._stencilFuncRef = value;
  10187. this._isStencilFuncDirty = true;
  10188. },
  10189. enumerable: true,
  10190. configurable: true
  10191. });
  10192. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10193. get: function () {
  10194. return this._stencilFuncMask;
  10195. },
  10196. set: function (value) {
  10197. if (this._stencilFuncMask === value) {
  10198. return;
  10199. }
  10200. this._stencilFuncMask = value;
  10201. this._isStencilFuncDirty = true;
  10202. },
  10203. enumerable: true,
  10204. configurable: true
  10205. });
  10206. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10207. get: function () {
  10208. return this._stencilOpStencilFail;
  10209. },
  10210. set: function (value) {
  10211. if (this._stencilOpStencilFail === value) {
  10212. return;
  10213. }
  10214. this._stencilOpStencilFail = value;
  10215. this._isStencilOpDirty = true;
  10216. },
  10217. enumerable: true,
  10218. configurable: true
  10219. });
  10220. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10221. get: function () {
  10222. return this._stencilOpDepthFail;
  10223. },
  10224. set: function (value) {
  10225. if (this._stencilOpDepthFail === value) {
  10226. return;
  10227. }
  10228. this._stencilOpDepthFail = value;
  10229. this._isStencilOpDirty = true;
  10230. },
  10231. enumerable: true,
  10232. configurable: true
  10233. });
  10234. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10235. get: function () {
  10236. return this._stencilOpStencilDepthPass;
  10237. },
  10238. set: function (value) {
  10239. if (this._stencilOpStencilDepthPass === value) {
  10240. return;
  10241. }
  10242. this._stencilOpStencilDepthPass = value;
  10243. this._isStencilOpDirty = true;
  10244. },
  10245. enumerable: true,
  10246. configurable: true
  10247. });
  10248. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10249. get: function () {
  10250. return this._stencilMask;
  10251. },
  10252. set: function (value) {
  10253. if (this._stencilMask === value) {
  10254. return;
  10255. }
  10256. this._stencilMask = value;
  10257. this._isStencilMaskDirty = true;
  10258. },
  10259. enumerable: true,
  10260. configurable: true
  10261. });
  10262. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10263. get: function () {
  10264. return this._stencilTest;
  10265. },
  10266. set: function (value) {
  10267. if (this._stencilTest === value) {
  10268. return;
  10269. }
  10270. this._stencilTest = value;
  10271. this._isStencilTestDirty = true;
  10272. },
  10273. enumerable: true,
  10274. configurable: true
  10275. });
  10276. _StencilState.prototype.reset = function () {
  10277. this._stencilTest = false;
  10278. this._stencilMask = 0xFF;
  10279. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10280. this._stencilFuncRef = 1;
  10281. this._stencilFuncMask = 0xFF;
  10282. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10283. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10284. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10285. this._isStencilTestDirty = true;
  10286. this._isStencilMaskDirty = true;
  10287. this._isStencilFuncDirty = true;
  10288. this._isStencilOpDirty = true;
  10289. };
  10290. _StencilState.prototype.apply = function (gl) {
  10291. if (!this.isDirty) {
  10292. return;
  10293. }
  10294. // Stencil test
  10295. if (this._isStencilTestDirty) {
  10296. if (this.stencilTest) {
  10297. gl.enable(gl.STENCIL_TEST);
  10298. }
  10299. else {
  10300. gl.disable(gl.STENCIL_TEST);
  10301. }
  10302. this._isStencilTestDirty = false;
  10303. }
  10304. // Stencil mask
  10305. if (this._isStencilMaskDirty) {
  10306. gl.stencilMask(this.stencilMask);
  10307. this._isStencilMaskDirty = false;
  10308. }
  10309. // Stencil func
  10310. if (this._isStencilFuncDirty) {
  10311. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10312. this._isStencilFuncDirty = false;
  10313. }
  10314. // Stencil op
  10315. if (this._isStencilOpDirty) {
  10316. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10317. this._isStencilOpDirty = false;
  10318. }
  10319. };
  10320. return _StencilState;
  10321. }());
  10322. BABYLON._StencilState = _StencilState;
  10323. })(BABYLON || (BABYLON = {}));
  10324. //# sourceMappingURL=babylon.stencilState.js.map
  10325. "use strict";
  10326. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10327. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10328. s = arguments[i];
  10329. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10330. t[p] = s[p];
  10331. }
  10332. return t;
  10333. };
  10334. var BABYLON;
  10335. (function (BABYLON) {
  10336. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10337. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10338. };
  10339. var compileRawShader = function (gl, source, type) {
  10340. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10341. gl.shaderSource(shader, source);
  10342. gl.compileShader(shader);
  10343. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10344. var log = gl.getShaderInfoLog(shader);
  10345. if (log) {
  10346. throw new Error(log);
  10347. }
  10348. }
  10349. if (!shader) {
  10350. throw new Error("Something went wrong while compile the shader.");
  10351. }
  10352. return shader;
  10353. };
  10354. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10355. var magFilter = gl.NEAREST;
  10356. var minFilter = gl.NEAREST;
  10357. switch (samplingMode) {
  10358. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10359. magFilter = gl.LINEAR;
  10360. if (generateMipMaps) {
  10361. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10362. }
  10363. else {
  10364. minFilter = gl.LINEAR;
  10365. }
  10366. break;
  10367. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10368. magFilter = gl.LINEAR;
  10369. if (generateMipMaps) {
  10370. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10371. }
  10372. else {
  10373. minFilter = gl.LINEAR;
  10374. }
  10375. break;
  10376. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10377. magFilter = gl.NEAREST;
  10378. if (generateMipMaps) {
  10379. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10380. }
  10381. else {
  10382. minFilter = gl.NEAREST;
  10383. }
  10384. break;
  10385. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10386. magFilter = gl.NEAREST;
  10387. if (generateMipMaps) {
  10388. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10389. }
  10390. else {
  10391. minFilter = gl.NEAREST;
  10392. }
  10393. break;
  10394. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10395. magFilter = gl.NEAREST;
  10396. if (generateMipMaps) {
  10397. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10398. }
  10399. else {
  10400. minFilter = gl.LINEAR;
  10401. }
  10402. break;
  10403. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10404. magFilter = gl.NEAREST;
  10405. if (generateMipMaps) {
  10406. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10407. }
  10408. else {
  10409. minFilter = gl.LINEAR;
  10410. }
  10411. break;
  10412. case BABYLON.Texture.NEAREST_LINEAR:
  10413. magFilter = gl.NEAREST;
  10414. minFilter = gl.LINEAR;
  10415. break;
  10416. case BABYLON.Texture.NEAREST_NEAREST:
  10417. magFilter = gl.NEAREST;
  10418. minFilter = gl.NEAREST;
  10419. break;
  10420. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10421. magFilter = gl.LINEAR;
  10422. if (generateMipMaps) {
  10423. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10424. }
  10425. else {
  10426. minFilter = gl.NEAREST;
  10427. }
  10428. break;
  10429. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  10430. magFilter = gl.LINEAR;
  10431. if (generateMipMaps) {
  10432. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10433. }
  10434. else {
  10435. minFilter = gl.NEAREST;
  10436. }
  10437. break;
  10438. case BABYLON.Texture.LINEAR_LINEAR:
  10439. magFilter = gl.LINEAR;
  10440. minFilter = gl.LINEAR;
  10441. break;
  10442. case BABYLON.Texture.LINEAR_NEAREST:
  10443. magFilter = gl.LINEAR;
  10444. minFilter = gl.NEAREST;
  10445. break;
  10446. }
  10447. return {
  10448. min: minFilter,
  10449. mag: magFilter
  10450. };
  10451. };
  10452. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  10453. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  10454. var img;
  10455. var onload = function () {
  10456. loadedImages[index] = img;
  10457. loadedImages._internalCount++;
  10458. if (scene) {
  10459. scene._removePendingData(img);
  10460. }
  10461. if (loadedImages._internalCount === 6) {
  10462. onfinish(loadedImages);
  10463. }
  10464. };
  10465. var onerror = function (message, exception) {
  10466. if (scene) {
  10467. scene._removePendingData(img);
  10468. }
  10469. if (onErrorCallBack) {
  10470. onErrorCallBack(message, exception);
  10471. }
  10472. };
  10473. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  10474. if (scene) {
  10475. scene._addPendingData(img);
  10476. }
  10477. };
  10478. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  10479. if (onError === void 0) { onError = null; }
  10480. var loadedImages = [];
  10481. loadedImages._internalCount = 0;
  10482. for (var index = 0; index < 6; index++) {
  10483. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  10484. }
  10485. };
  10486. var BufferPointer = /** @class */ (function () {
  10487. function BufferPointer() {
  10488. }
  10489. return BufferPointer;
  10490. }());
  10491. var InstancingAttributeInfo = /** @class */ (function () {
  10492. function InstancingAttributeInfo() {
  10493. }
  10494. return InstancingAttributeInfo;
  10495. }());
  10496. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  10497. /**
  10498. * Define options used to create a render target texture
  10499. */
  10500. var RenderTargetCreationOptions = /** @class */ (function () {
  10501. function RenderTargetCreationOptions() {
  10502. }
  10503. return RenderTargetCreationOptions;
  10504. }());
  10505. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  10506. /**
  10507. * Define options used to create a depth texture
  10508. */
  10509. var DepthTextureCreationOptions = /** @class */ (function () {
  10510. function DepthTextureCreationOptions() {
  10511. }
  10512. return DepthTextureCreationOptions;
  10513. }());
  10514. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  10515. /**
  10516. * Regroup several parameters relative to the browser in use
  10517. */
  10518. var EngineCapabilities = /** @class */ (function () {
  10519. function EngineCapabilities() {
  10520. }
  10521. return EngineCapabilities;
  10522. }());
  10523. BABYLON.EngineCapabilities = EngineCapabilities;
  10524. /**
  10525. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  10526. */
  10527. var Engine = /** @class */ (function () {
  10528. /**
  10529. * @constructor
  10530. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  10531. * @param antialias defines enable antialiasing (default: false)
  10532. * @param options defines further options to be sent to the getContext() function
  10533. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  10534. */
  10535. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  10536. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  10537. var _this = this;
  10538. // Public members
  10539. this.forcePOTTextures = false;
  10540. this.isFullscreen = false;
  10541. this.isPointerLock = false;
  10542. this.cullBackFaces = true;
  10543. this.renderEvenInBackground = true;
  10544. this.preventCacheWipeBetweenFrames = false;
  10545. // To enable/disable IDB support and avoid XHR on .manifest
  10546. this.enableOfflineSupport = false;
  10547. this.scenes = new Array();
  10548. this.postProcesses = new Array();
  10549. // Observables
  10550. /**
  10551. * Observable event triggered each time the rendering canvas is resized
  10552. */
  10553. this.onResizeObservable = new BABYLON.Observable();
  10554. /**
  10555. * Observable event triggered each time the canvas loses focus
  10556. */
  10557. this.onCanvasBlurObservable = new BABYLON.Observable();
  10558. /**
  10559. * Observable event triggered each time the canvas gains focus
  10560. */
  10561. this.onCanvasFocusObservable = new BABYLON.Observable();
  10562. /**
  10563. * Observable event triggered each time the canvas receives pointerout event
  10564. */
  10565. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  10566. /**
  10567. * Observable event triggered before each texture is initialized
  10568. */
  10569. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  10570. //WebVR
  10571. this._vrDisplay = undefined;
  10572. this._vrSupported = false;
  10573. this._vrExclusivePointerMode = false;
  10574. // Uniform buffers list
  10575. this.disableUniformBuffers = false;
  10576. this._uniformBuffers = new Array();
  10577. // Observables
  10578. /**
  10579. * Observable raised when the engine begins a new frame
  10580. */
  10581. this.onBeginFrameObservable = new BABYLON.Observable();
  10582. /**
  10583. * Observable raised when the engine ends the current frame
  10584. */
  10585. this.onEndFrameObservable = new BABYLON.Observable();
  10586. /**
  10587. * Observable raised when the engine is about to compile a shader
  10588. */
  10589. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  10590. /**
  10591. * Observable raised when the engine has jsut compiled a shader
  10592. */
  10593. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  10594. this._windowIsBackground = false;
  10595. this._webGLVersion = 1.0;
  10596. this._badOS = false;
  10597. this._badDesktopOS = false;
  10598. /**
  10599. * Gets or sets a value indicating if we want to disable texture binding optmization.
  10600. * This could be required on some buggy drivers which wants to have textures bound in a progressive order
  10601. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is.
  10602. */
  10603. this.disableTextureBindingOptimization = false;
  10604. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  10605. this.onVRRequestPresentComplete = new BABYLON.Observable();
  10606. this.onVRRequestPresentStart = new BABYLON.Observable();
  10607. this._colorWrite = true;
  10608. this._drawCalls = new BABYLON.PerfCounter();
  10609. this._textureCollisions = new BABYLON.PerfCounter();
  10610. this._renderingQueueLaunched = false;
  10611. this._activeRenderLoops = new Array();
  10612. // Deterministic lockstepMaxSteps
  10613. this._deterministicLockstep = false;
  10614. this._lockstepMaxSteps = 4;
  10615. // Lost context
  10616. this.onContextLostObservable = new BABYLON.Observable();
  10617. this.onContextRestoredObservable = new BABYLON.Observable();
  10618. this._contextWasLost = false;
  10619. this._doNotHandleContextLost = false;
  10620. // FPS
  10621. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  10622. this._fps = 60;
  10623. this._deltaTime = 0;
  10624. /**
  10625. * Turn this value on if you want to pause FPS computation when in background
  10626. */
  10627. this.disablePerformanceMonitorInBackground = false;
  10628. // States
  10629. this._depthCullingState = new BABYLON._DepthCullingState();
  10630. this._stencilState = new BABYLON._StencilState();
  10631. this._alphaState = new BABYLON._AlphaState();
  10632. this._alphaMode = Engine.ALPHA_DISABLE;
  10633. // Cache
  10634. this._internalTexturesCache = new Array();
  10635. this._activeChannel = 0;
  10636. this._currentTextureChannel = -1;
  10637. this._boundTexturesCache = {};
  10638. this._compiledEffects = {};
  10639. this._vertexAttribArraysEnabled = [];
  10640. this._uintIndicesCurrentlySet = false;
  10641. this._currentBoundBuffer = new Array();
  10642. this._currentBufferPointers = new Array();
  10643. this._currentInstanceLocations = new Array();
  10644. this._currentInstanceBuffers = new Array();
  10645. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10646. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  10647. this._vaoRecordInProgress = false;
  10648. this._mustWipeVertexAttributes = false;
  10649. this._nextFreeTextureSlots = new Array();
  10650. this._maxSimultaneousTextures = 0;
  10651. this._activeRequests = new Array();
  10652. // Hardware supported Compressed Textures
  10653. this._texturesSupported = new Array();
  10654. this._onVRFullScreenTriggered = function () {
  10655. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  10656. //get the old size before we change
  10657. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  10658. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  10659. //get the width and height, change the render size
  10660. var leftEye = _this._vrDisplay.getEyeParameters('left');
  10661. _this.setHardwareScalingLevel(1);
  10662. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  10663. }
  10664. else {
  10665. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  10666. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  10667. }
  10668. };
  10669. this._boundUniforms = {};
  10670. // Register promises
  10671. BABYLON.PromisePolyfill.Apply();
  10672. var canvas = null;
  10673. Engine.Instances.push(this);
  10674. if (!canvasOrContext) {
  10675. return;
  10676. }
  10677. options = options || {};
  10678. if (canvasOrContext.getContext) {
  10679. canvas = canvasOrContext;
  10680. this._renderingCanvas = canvas;
  10681. if (antialias != null) {
  10682. options.antialias = antialias;
  10683. }
  10684. if (options.deterministicLockstep === undefined) {
  10685. options.deterministicLockstep = false;
  10686. }
  10687. if (options.lockstepMaxSteps === undefined) {
  10688. options.lockstepMaxSteps = 4;
  10689. }
  10690. if (options.preserveDrawingBuffer === undefined) {
  10691. options.preserveDrawingBuffer = false;
  10692. }
  10693. if (options.audioEngine === undefined) {
  10694. options.audioEngine = true;
  10695. }
  10696. if (options.stencil === undefined) {
  10697. options.stencil = true;
  10698. }
  10699. this._deterministicLockstep = options.deterministicLockstep;
  10700. this._lockstepMaxSteps = options.lockstepMaxSteps;
  10701. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  10702. // Exceptions
  10703. if (navigator && navigator.userAgent) {
  10704. var ua = navigator.userAgent;
  10705. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  10706. var exception = _a[_i];
  10707. var key = exception.key;
  10708. var targets = exception.targets;
  10709. if (ua.indexOf(key) > -1) {
  10710. if (exception.capture && exception.captureConstraint) {
  10711. var capture = exception.capture;
  10712. var constraint = exception.captureConstraint;
  10713. var regex = new RegExp(capture);
  10714. var matches = regex.exec(ua);
  10715. if (matches && matches.length > 0) {
  10716. var capturedValue = parseInt(matches[matches.length - 1]);
  10717. if (capturedValue >= constraint) {
  10718. continue;
  10719. }
  10720. }
  10721. }
  10722. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  10723. var target = targets_1[_b];
  10724. switch (target) {
  10725. case "uniformBuffer":
  10726. this.disableUniformBuffers = true;
  10727. break;
  10728. case "textureBindingOptimization":
  10729. this.disableTextureBindingOptimization = true;
  10730. break;
  10731. }
  10732. }
  10733. }
  10734. }
  10735. }
  10736. // GL
  10737. if (!options.disableWebGL2Support) {
  10738. try {
  10739. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  10740. if (this._gl) {
  10741. this._webGLVersion = 2.0;
  10742. }
  10743. }
  10744. catch (e) {
  10745. // Do nothing
  10746. }
  10747. }
  10748. if (!this._gl) {
  10749. if (!canvas) {
  10750. throw new Error("The provided canvas is null or undefined.");
  10751. }
  10752. try {
  10753. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  10754. }
  10755. catch (e) {
  10756. throw new Error("WebGL not supported");
  10757. }
  10758. }
  10759. if (!this._gl) {
  10760. throw new Error("WebGL not supported");
  10761. }
  10762. this._onCanvasFocus = function () {
  10763. _this.onCanvasFocusObservable.notifyObservers(_this);
  10764. };
  10765. this._onCanvasBlur = function () {
  10766. _this.onCanvasBlurObservable.notifyObservers(_this);
  10767. };
  10768. canvas.addEventListener("focus", this._onCanvasFocus);
  10769. canvas.addEventListener("blur", this._onCanvasBlur);
  10770. this._onBlur = function () {
  10771. if (_this.disablePerformanceMonitorInBackground) {
  10772. _this._performanceMonitor.disable();
  10773. }
  10774. _this._windowIsBackground = true;
  10775. };
  10776. this._onFocus = function () {
  10777. if (_this.disablePerformanceMonitorInBackground) {
  10778. _this._performanceMonitor.enable();
  10779. }
  10780. _this._windowIsBackground = false;
  10781. };
  10782. this._onCanvasPointerOut = function (ev) {
  10783. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  10784. };
  10785. window.addEventListener("blur", this._onBlur);
  10786. window.addEventListener("focus", this._onFocus);
  10787. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  10788. // Context lost
  10789. if (!this._doNotHandleContextLost) {
  10790. this._onContextLost = function (evt) {
  10791. evt.preventDefault();
  10792. _this._contextWasLost = true;
  10793. BABYLON.Tools.Warn("WebGL context lost.");
  10794. _this.onContextLostObservable.notifyObservers(_this);
  10795. };
  10796. this._onContextRestored = function (evt) {
  10797. // Adding a timeout to avoid race condition at browser level
  10798. setTimeout(function () {
  10799. // Rebuild gl context
  10800. _this._initGLContext();
  10801. // Rebuild effects
  10802. _this._rebuildEffects();
  10803. // Rebuild textures
  10804. _this._rebuildInternalTextures();
  10805. // Rebuild buffers
  10806. _this._rebuildBuffers();
  10807. // Cache
  10808. _this.wipeCaches(true);
  10809. BABYLON.Tools.Warn("WebGL context successfully restored.");
  10810. _this.onContextRestoredObservable.notifyObservers(_this);
  10811. _this._contextWasLost = false;
  10812. }, 0);
  10813. };
  10814. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  10815. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  10816. }
  10817. }
  10818. else {
  10819. this._gl = canvasOrContext;
  10820. this._renderingCanvas = this._gl.canvas;
  10821. if (this._gl.renderbufferStorageMultisample) {
  10822. this._webGLVersion = 2.0;
  10823. }
  10824. options.stencil = this._gl.getContextAttributes().stencil;
  10825. }
  10826. // Viewport
  10827. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  10828. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  10829. this.resize();
  10830. this._isStencilEnable = options.stencil ? true : false;
  10831. this._initGLContext();
  10832. if (canvas) {
  10833. // Fullscreen
  10834. this._onFullscreenChange = function () {
  10835. if (document.fullscreen !== undefined) {
  10836. _this.isFullscreen = document.fullscreen;
  10837. }
  10838. else if (document.mozFullScreen !== undefined) {
  10839. _this.isFullscreen = document.mozFullScreen;
  10840. }
  10841. else if (document.webkitIsFullScreen !== undefined) {
  10842. _this.isFullscreen = document.webkitIsFullScreen;
  10843. }
  10844. else if (document.msIsFullScreen !== undefined) {
  10845. _this.isFullscreen = document.msIsFullScreen;
  10846. }
  10847. // Pointer lock
  10848. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  10849. canvas.requestPointerLock = canvas.requestPointerLock ||
  10850. canvas.msRequestPointerLock ||
  10851. canvas.mozRequestPointerLock ||
  10852. canvas.webkitRequestPointerLock;
  10853. if (canvas.requestPointerLock) {
  10854. canvas.requestPointerLock();
  10855. }
  10856. }
  10857. };
  10858. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  10859. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  10860. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  10861. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  10862. // Pointer lock
  10863. this._onPointerLockChange = function () {
  10864. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  10865. document.webkitPointerLockElement === canvas ||
  10866. document.msPointerLockElement === canvas ||
  10867. document.pointerLockElement === canvas);
  10868. };
  10869. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  10870. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  10871. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  10872. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  10873. this._onVRDisplayPointerRestricted = function () {
  10874. if (canvas) {
  10875. canvas.requestPointerLock();
  10876. }
  10877. };
  10878. this._onVRDisplayPointerUnrestricted = function () {
  10879. document.exitPointerLock();
  10880. };
  10881. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  10882. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  10883. }
  10884. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  10885. Engine.audioEngine = new BABYLON.AudioEngine();
  10886. }
  10887. // Prepare buffer pointers
  10888. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10889. this._currentBufferPointers[i] = new BufferPointer();
  10890. }
  10891. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  10892. // Load WebVR Devices
  10893. if (options.autoEnableWebVR) {
  10894. this.initWebVR();
  10895. }
  10896. // Detect if we are running on a faulty buggy OS.
  10897. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  10898. // Detect if we are running on a faulty buggy desktop OS.
  10899. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  10900. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  10901. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  10902. }
  10903. Object.defineProperty(Engine, "LastCreatedEngine", {
  10904. get: function () {
  10905. if (Engine.Instances.length === 0) {
  10906. return null;
  10907. }
  10908. return Engine.Instances[Engine.Instances.length - 1];
  10909. },
  10910. enumerable: true,
  10911. configurable: true
  10912. });
  10913. Object.defineProperty(Engine, "LastCreatedScene", {
  10914. get: function () {
  10915. var lastCreatedEngine = Engine.LastCreatedEngine;
  10916. if (!lastCreatedEngine) {
  10917. return null;
  10918. }
  10919. if (lastCreatedEngine.scenes.length === 0) {
  10920. return null;
  10921. }
  10922. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  10923. },
  10924. enumerable: true,
  10925. configurable: true
  10926. });
  10927. /**
  10928. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  10929. */
  10930. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  10931. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  10932. var engine = Engine.Instances[engineIndex];
  10933. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  10934. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  10935. }
  10936. }
  10937. };
  10938. Object.defineProperty(Engine, "NEVER", {
  10939. get: function () {
  10940. return Engine._NEVER;
  10941. },
  10942. enumerable: true,
  10943. configurable: true
  10944. });
  10945. Object.defineProperty(Engine, "ALWAYS", {
  10946. get: function () {
  10947. return Engine._ALWAYS;
  10948. },
  10949. enumerable: true,
  10950. configurable: true
  10951. });
  10952. Object.defineProperty(Engine, "LESS", {
  10953. get: function () {
  10954. return Engine._LESS;
  10955. },
  10956. enumerable: true,
  10957. configurable: true
  10958. });
  10959. Object.defineProperty(Engine, "EQUAL", {
  10960. get: function () {
  10961. return Engine._EQUAL;
  10962. },
  10963. enumerable: true,
  10964. configurable: true
  10965. });
  10966. Object.defineProperty(Engine, "LEQUAL", {
  10967. get: function () {
  10968. return Engine._LEQUAL;
  10969. },
  10970. enumerable: true,
  10971. configurable: true
  10972. });
  10973. Object.defineProperty(Engine, "GREATER", {
  10974. get: function () {
  10975. return Engine._GREATER;
  10976. },
  10977. enumerable: true,
  10978. configurable: true
  10979. });
  10980. Object.defineProperty(Engine, "GEQUAL", {
  10981. get: function () {
  10982. return Engine._GEQUAL;
  10983. },
  10984. enumerable: true,
  10985. configurable: true
  10986. });
  10987. Object.defineProperty(Engine, "NOTEQUAL", {
  10988. get: function () {
  10989. return Engine._NOTEQUAL;
  10990. },
  10991. enumerable: true,
  10992. configurable: true
  10993. });
  10994. Object.defineProperty(Engine, "KEEP", {
  10995. get: function () {
  10996. return Engine._KEEP;
  10997. },
  10998. enumerable: true,
  10999. configurable: true
  11000. });
  11001. Object.defineProperty(Engine, "REPLACE", {
  11002. get: function () {
  11003. return Engine._REPLACE;
  11004. },
  11005. enumerable: true,
  11006. configurable: true
  11007. });
  11008. Object.defineProperty(Engine, "INCR", {
  11009. get: function () {
  11010. return Engine._INCR;
  11011. },
  11012. enumerable: true,
  11013. configurable: true
  11014. });
  11015. Object.defineProperty(Engine, "DECR", {
  11016. get: function () {
  11017. return Engine._DECR;
  11018. },
  11019. enumerable: true,
  11020. configurable: true
  11021. });
  11022. Object.defineProperty(Engine, "INVERT", {
  11023. get: function () {
  11024. return Engine._INVERT;
  11025. },
  11026. enumerable: true,
  11027. configurable: true
  11028. });
  11029. Object.defineProperty(Engine, "INCR_WRAP", {
  11030. get: function () {
  11031. return Engine._INCR_WRAP;
  11032. },
  11033. enumerable: true,
  11034. configurable: true
  11035. });
  11036. Object.defineProperty(Engine, "DECR_WRAP", {
  11037. get: function () {
  11038. return Engine._DECR_WRAP;
  11039. },
  11040. enumerable: true,
  11041. configurable: true
  11042. });
  11043. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11044. get: function () {
  11045. return Engine._ALPHA_DISABLE;
  11046. },
  11047. enumerable: true,
  11048. configurable: true
  11049. });
  11050. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11051. get: function () {
  11052. return Engine._ALPHA_ONEONE;
  11053. },
  11054. enumerable: true,
  11055. configurable: true
  11056. });
  11057. Object.defineProperty(Engine, "ALPHA_ADD", {
  11058. get: function () {
  11059. return Engine._ALPHA_ADD;
  11060. },
  11061. enumerable: true,
  11062. configurable: true
  11063. });
  11064. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11065. get: function () {
  11066. return Engine._ALPHA_COMBINE;
  11067. },
  11068. enumerable: true,
  11069. configurable: true
  11070. });
  11071. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11072. get: function () {
  11073. return Engine._ALPHA_SUBTRACT;
  11074. },
  11075. enumerable: true,
  11076. configurable: true
  11077. });
  11078. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11079. get: function () {
  11080. return Engine._ALPHA_MULTIPLY;
  11081. },
  11082. enumerable: true,
  11083. configurable: true
  11084. });
  11085. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11086. get: function () {
  11087. return Engine._ALPHA_MAXIMIZED;
  11088. },
  11089. enumerable: true,
  11090. configurable: true
  11091. });
  11092. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11093. get: function () {
  11094. return Engine._ALPHA_PREMULTIPLIED;
  11095. },
  11096. enumerable: true,
  11097. configurable: true
  11098. });
  11099. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11100. get: function () {
  11101. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11102. },
  11103. enumerable: true,
  11104. configurable: true
  11105. });
  11106. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11107. get: function () {
  11108. return Engine._ALPHA_INTERPOLATE;
  11109. },
  11110. enumerable: true,
  11111. configurable: true
  11112. });
  11113. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11114. get: function () {
  11115. return Engine._ALPHA_SCREENMODE;
  11116. },
  11117. enumerable: true,
  11118. configurable: true
  11119. });
  11120. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11121. get: function () {
  11122. return Engine._DELAYLOADSTATE_NONE;
  11123. },
  11124. enumerable: true,
  11125. configurable: true
  11126. });
  11127. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11128. get: function () {
  11129. return Engine._DELAYLOADSTATE_LOADED;
  11130. },
  11131. enumerable: true,
  11132. configurable: true
  11133. });
  11134. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11135. get: function () {
  11136. return Engine._DELAYLOADSTATE_LOADING;
  11137. },
  11138. enumerable: true,
  11139. configurable: true
  11140. });
  11141. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11142. get: function () {
  11143. return Engine._DELAYLOADSTATE_NOTLOADED;
  11144. },
  11145. enumerable: true,
  11146. configurable: true
  11147. });
  11148. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11149. get: function () {
  11150. return Engine._TEXTUREFORMAT_ALPHA;
  11151. },
  11152. enumerable: true,
  11153. configurable: true
  11154. });
  11155. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11156. get: function () {
  11157. return Engine._TEXTUREFORMAT_LUMINANCE;
  11158. },
  11159. enumerable: true,
  11160. configurable: true
  11161. });
  11162. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  11163. /**
  11164. * R32F
  11165. */
  11166. get: function () {
  11167. return Engine._TEXTUREFORMAT_R32F;
  11168. },
  11169. enumerable: true,
  11170. configurable: true
  11171. });
  11172. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  11173. /**
  11174. * RG32F
  11175. */
  11176. get: function () {
  11177. return Engine._TEXTUREFORMAT_RG32F;
  11178. },
  11179. enumerable: true,
  11180. configurable: true
  11181. });
  11182. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11183. /**
  11184. * RGB32F
  11185. */
  11186. get: function () {
  11187. return Engine._TEXTUREFORMAT_RGB32F;
  11188. },
  11189. enumerable: true,
  11190. configurable: true
  11191. });
  11192. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11193. /**
  11194. * RGBA32F
  11195. */
  11196. get: function () {
  11197. return Engine._TEXTUREFORMAT_RGBA32F;
  11198. },
  11199. enumerable: true,
  11200. configurable: true
  11201. });
  11202. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11203. get: function () {
  11204. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11205. },
  11206. enumerable: true,
  11207. configurable: true
  11208. });
  11209. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11210. get: function () {
  11211. return Engine._TEXTUREFORMAT_RGB;
  11212. },
  11213. enumerable: true,
  11214. configurable: true
  11215. });
  11216. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11217. get: function () {
  11218. return Engine._TEXTUREFORMAT_RGBA;
  11219. },
  11220. enumerable: true,
  11221. configurable: true
  11222. });
  11223. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11224. get: function () {
  11225. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11226. },
  11227. enumerable: true,
  11228. configurable: true
  11229. });
  11230. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11231. get: function () {
  11232. return Engine._TEXTURETYPE_FLOAT;
  11233. },
  11234. enumerable: true,
  11235. configurable: true
  11236. });
  11237. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11238. get: function () {
  11239. return Engine._TEXTURETYPE_HALF_FLOAT;
  11240. },
  11241. enumerable: true,
  11242. configurable: true
  11243. });
  11244. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11245. get: function () {
  11246. return Engine._SCALEMODE_FLOOR;
  11247. },
  11248. enumerable: true,
  11249. configurable: true
  11250. });
  11251. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11252. get: function () {
  11253. return Engine._SCALEMODE_NEAREST;
  11254. },
  11255. enumerable: true,
  11256. configurable: true
  11257. });
  11258. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11259. get: function () {
  11260. return Engine._SCALEMODE_CEILING;
  11261. },
  11262. enumerable: true,
  11263. configurable: true
  11264. });
  11265. Object.defineProperty(Engine, "Version", {
  11266. get: function () {
  11267. return "3.2.0-beta.1";
  11268. },
  11269. enumerable: true,
  11270. configurable: true
  11271. });
  11272. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11273. get: function () {
  11274. return this._vrExclusivePointerMode;
  11275. },
  11276. enumerable: true,
  11277. configurable: true
  11278. });
  11279. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11280. get: function () {
  11281. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11282. },
  11283. enumerable: true,
  11284. configurable: true
  11285. });
  11286. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11287. get: function () {
  11288. return this._webGLVersion < 2 || this.forcePOTTextures;
  11289. },
  11290. enumerable: true,
  11291. configurable: true
  11292. });
  11293. Object.defineProperty(Engine.prototype, "badOS", {
  11294. get: function () {
  11295. return this._badOS;
  11296. },
  11297. enumerable: true,
  11298. configurable: true
  11299. });
  11300. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  11301. get: function () {
  11302. return this._badDesktopOS;
  11303. },
  11304. enumerable: true,
  11305. configurable: true
  11306. });
  11307. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  11308. get: function () {
  11309. return this._performanceMonitor;
  11310. },
  11311. enumerable: true,
  11312. configurable: true
  11313. });
  11314. Object.defineProperty(Engine.prototype, "texturesSupported", {
  11315. get: function () {
  11316. return this._texturesSupported;
  11317. },
  11318. enumerable: true,
  11319. configurable: true
  11320. });
  11321. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  11322. get: function () {
  11323. return this._textureFormatInUse;
  11324. },
  11325. enumerable: true,
  11326. configurable: true
  11327. });
  11328. Object.defineProperty(Engine.prototype, "currentViewport", {
  11329. get: function () {
  11330. return this._cachedViewport;
  11331. },
  11332. enumerable: true,
  11333. configurable: true
  11334. });
  11335. Object.defineProperty(Engine.prototype, "emptyTexture", {
  11336. // Empty texture
  11337. get: function () {
  11338. if (!this._emptyTexture) {
  11339. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11340. }
  11341. return this._emptyTexture;
  11342. },
  11343. enumerable: true,
  11344. configurable: true
  11345. });
  11346. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  11347. get: function () {
  11348. if (!this._emptyTexture3D) {
  11349. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11350. }
  11351. return this._emptyTexture3D;
  11352. },
  11353. enumerable: true,
  11354. configurable: true
  11355. });
  11356. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  11357. get: function () {
  11358. if (!this._emptyCubeTexture) {
  11359. var faceData = new Uint8Array(4);
  11360. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  11361. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11362. }
  11363. return this._emptyCubeTexture;
  11364. },
  11365. enumerable: true,
  11366. configurable: true
  11367. });
  11368. Engine.prototype._rebuildInternalTextures = function () {
  11369. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  11370. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  11371. var internalTexture = currentState_1[_i];
  11372. internalTexture._rebuild();
  11373. }
  11374. };
  11375. Engine.prototype._rebuildEffects = function () {
  11376. for (var key in this._compiledEffects) {
  11377. var effect = this._compiledEffects[key];
  11378. effect._prepareEffect();
  11379. }
  11380. BABYLON.Effect.ResetCache();
  11381. };
  11382. Engine.prototype._rebuildBuffers = function () {
  11383. // Index / Vertex
  11384. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  11385. var scene = _a[_i];
  11386. scene.resetCachedMaterial();
  11387. scene._rebuildGeometries();
  11388. scene._rebuildTextures();
  11389. }
  11390. // Uniforms
  11391. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  11392. var uniformBuffer = _c[_b];
  11393. uniformBuffer._rebuild();
  11394. }
  11395. };
  11396. Engine.prototype._initGLContext = function () {
  11397. // Caps
  11398. this._caps = new EngineCapabilities();
  11399. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  11400. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  11401. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  11402. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  11403. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  11404. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  11405. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  11406. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  11407. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  11408. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  11409. // Infos
  11410. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  11411. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  11412. if (rendererInfo != null) {
  11413. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  11414. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  11415. }
  11416. if (!this._glVendor) {
  11417. this._glVendor = "Unknown vendor";
  11418. }
  11419. if (!this._glRenderer) {
  11420. this._glRenderer = "Unknown renderer";
  11421. }
  11422. // Constants
  11423. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  11424. if (this._gl.RGBA16F !== 0x881A) {
  11425. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  11426. }
  11427. if (this._gl.RGBA32F !== 0x8814) {
  11428. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  11429. }
  11430. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  11431. this._gl.DEPTH24_STENCIL8 = 35056;
  11432. }
  11433. // Extensions
  11434. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  11435. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  11436. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  11437. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  11438. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  11439. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  11440. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  11441. 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');
  11442. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  11443. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  11444. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  11445. this._caps.highPrecisionShaderSupported = true;
  11446. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  11447. if (this._caps.timerQuery) {
  11448. if (this._webGLVersion === 1) {
  11449. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  11450. }
  11451. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  11452. }
  11453. // Checks if some of the format renders first to allow the use of webgl inspector.
  11454. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  11455. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  11456. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  11457. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  11458. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  11459. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  11460. if (this._webGLVersion > 1) {
  11461. this._gl.HALF_FLOAT_OES = 0x140B;
  11462. }
  11463. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  11464. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  11465. // Draw buffers
  11466. if (this._webGLVersion > 1) {
  11467. this._caps.drawBuffersExtension = true;
  11468. }
  11469. else {
  11470. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  11471. if (drawBuffersExtension !== null) {
  11472. this._caps.drawBuffersExtension = true;
  11473. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  11474. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  11475. for (var i = 0; i < 16; i++) {
  11476. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  11477. }
  11478. }
  11479. else {
  11480. this._caps.drawBuffersExtension = false;
  11481. }
  11482. }
  11483. // Depth Texture
  11484. if (this._webGLVersion > 1) {
  11485. this._caps.depthTextureExtension = true;
  11486. }
  11487. else {
  11488. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  11489. if (depthTextureExtension != null) {
  11490. this._caps.depthTextureExtension = true;
  11491. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  11492. }
  11493. }
  11494. // Vertex array object
  11495. if (this._webGLVersion > 1) {
  11496. this._caps.vertexArrayObject = true;
  11497. }
  11498. else {
  11499. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  11500. if (vertexArrayObjectExtension != null) {
  11501. this._caps.vertexArrayObject = true;
  11502. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  11503. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  11504. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  11505. }
  11506. else {
  11507. this._caps.vertexArrayObject = false;
  11508. }
  11509. }
  11510. // Instances count
  11511. if (this._webGLVersion > 1) {
  11512. this._caps.instancedArrays = true;
  11513. }
  11514. else {
  11515. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  11516. if (instanceExtension != null) {
  11517. this._caps.instancedArrays = true;
  11518. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  11519. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  11520. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  11521. }
  11522. else {
  11523. this._caps.instancedArrays = false;
  11524. }
  11525. }
  11526. // Intelligently add supported compressed formats in order to check for.
  11527. // Check for ASTC support first as it is most powerful and to be very cross platform.
  11528. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  11529. // Likely no hardware which supports both PVR & DXT, so order matters little.
  11530. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  11531. if (this._caps.astc)
  11532. this.texturesSupported.push('-astc.ktx');
  11533. if (this._caps.s3tc)
  11534. this.texturesSupported.push('-dxt.ktx');
  11535. if (this._caps.pvrtc)
  11536. this.texturesSupported.push('-pvrtc.ktx');
  11537. if (this._caps.etc2)
  11538. this.texturesSupported.push('-etc2.ktx');
  11539. if (this._caps.etc1)
  11540. this.texturesSupported.push('-etc1.ktx');
  11541. if (this._gl.getShaderPrecisionFormat) {
  11542. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  11543. if (highp) {
  11544. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  11545. }
  11546. }
  11547. // Depth buffer
  11548. this.setDepthBuffer(true);
  11549. this.setDepthFunctionToLessOrEqual();
  11550. this.setDepthWrite(true);
  11551. // Texture maps
  11552. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  11553. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11554. this._nextFreeTextureSlots.push(slot);
  11555. }
  11556. };
  11557. Object.defineProperty(Engine.prototype, "webGLVersion", {
  11558. get: function () {
  11559. return this._webGLVersion;
  11560. },
  11561. enumerable: true,
  11562. configurable: true
  11563. });
  11564. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  11565. /**
  11566. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  11567. */
  11568. get: function () {
  11569. return this._isStencilEnable;
  11570. },
  11571. enumerable: true,
  11572. configurable: true
  11573. });
  11574. Engine.prototype._prepareWorkingCanvas = function () {
  11575. if (this._workingCanvas) {
  11576. return;
  11577. }
  11578. this._workingCanvas = document.createElement("canvas");
  11579. var context = this._workingCanvas.getContext("2d");
  11580. if (context) {
  11581. this._workingContext = context;
  11582. }
  11583. };
  11584. Engine.prototype.resetTextureCache = function () {
  11585. for (var key in this._boundTexturesCache) {
  11586. var boundTexture = this._boundTexturesCache[key];
  11587. if (boundTexture) {
  11588. this._removeDesignatedSlot(boundTexture);
  11589. }
  11590. this._boundTexturesCache[key] = null;
  11591. }
  11592. if (!this.disableTextureBindingOptimization) {
  11593. this._nextFreeTextureSlots = [];
  11594. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  11595. this._nextFreeTextureSlots.push(slot);
  11596. }
  11597. }
  11598. this._currentTextureChannel = -1;
  11599. };
  11600. Engine.prototype.isDeterministicLockStep = function () {
  11601. return this._deterministicLockstep;
  11602. };
  11603. Engine.prototype.getLockstepMaxSteps = function () {
  11604. return this._lockstepMaxSteps;
  11605. };
  11606. Engine.prototype.getGlInfo = function () {
  11607. return {
  11608. vendor: this._glVendor,
  11609. renderer: this._glRenderer,
  11610. version: this._glVersion
  11611. };
  11612. };
  11613. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  11614. if (useScreen === void 0) { useScreen = false; }
  11615. var viewport = camera.viewport;
  11616. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  11617. };
  11618. Engine.prototype.getRenderWidth = function (useScreen) {
  11619. if (useScreen === void 0) { useScreen = false; }
  11620. if (!useScreen && this._currentRenderTarget) {
  11621. return this._currentRenderTarget.width;
  11622. }
  11623. return this._gl.drawingBufferWidth;
  11624. };
  11625. Engine.prototype.getRenderHeight = function (useScreen) {
  11626. if (useScreen === void 0) { useScreen = false; }
  11627. if (!useScreen && this._currentRenderTarget) {
  11628. return this._currentRenderTarget.height;
  11629. }
  11630. return this._gl.drawingBufferHeight;
  11631. };
  11632. Engine.prototype.getRenderingCanvas = function () {
  11633. return this._renderingCanvas;
  11634. };
  11635. Engine.prototype.getRenderingCanvasClientRect = function () {
  11636. if (!this._renderingCanvas) {
  11637. return null;
  11638. }
  11639. return this._renderingCanvas.getBoundingClientRect();
  11640. };
  11641. Engine.prototype.setHardwareScalingLevel = function (level) {
  11642. this._hardwareScalingLevel = level;
  11643. this.resize();
  11644. };
  11645. Engine.prototype.getHardwareScalingLevel = function () {
  11646. return this._hardwareScalingLevel;
  11647. };
  11648. Engine.prototype.getLoadedTexturesCache = function () {
  11649. return this._internalTexturesCache;
  11650. };
  11651. Engine.prototype.getCaps = function () {
  11652. return this._caps;
  11653. };
  11654. Object.defineProperty(Engine.prototype, "drawCalls", {
  11655. /** The number of draw calls submitted last frame */
  11656. get: function () {
  11657. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  11658. return 0;
  11659. },
  11660. enumerable: true,
  11661. configurable: true
  11662. });
  11663. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  11664. get: function () {
  11665. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  11666. return null;
  11667. },
  11668. enumerable: true,
  11669. configurable: true
  11670. });
  11671. Engine.prototype.getDepthFunction = function () {
  11672. return this._depthCullingState.depthFunc;
  11673. };
  11674. Engine.prototype.setDepthFunction = function (depthFunc) {
  11675. this._depthCullingState.depthFunc = depthFunc;
  11676. };
  11677. Engine.prototype.setDepthFunctionToGreater = function () {
  11678. this._depthCullingState.depthFunc = this._gl.GREATER;
  11679. };
  11680. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  11681. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  11682. };
  11683. Engine.prototype.setDepthFunctionToLess = function () {
  11684. this._depthCullingState.depthFunc = this._gl.LESS;
  11685. };
  11686. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  11687. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  11688. };
  11689. Engine.prototype.getStencilBuffer = function () {
  11690. return this._stencilState.stencilTest;
  11691. };
  11692. Engine.prototype.setStencilBuffer = function (enable) {
  11693. this._stencilState.stencilTest = enable;
  11694. };
  11695. Engine.prototype.getStencilMask = function () {
  11696. return this._stencilState.stencilMask;
  11697. };
  11698. Engine.prototype.setStencilMask = function (mask) {
  11699. this._stencilState.stencilMask = mask;
  11700. };
  11701. Engine.prototype.getStencilFunction = function () {
  11702. return this._stencilState.stencilFunc;
  11703. };
  11704. Engine.prototype.getStencilFunctionReference = function () {
  11705. return this._stencilState.stencilFuncRef;
  11706. };
  11707. Engine.prototype.getStencilFunctionMask = function () {
  11708. return this._stencilState.stencilFuncMask;
  11709. };
  11710. Engine.prototype.setStencilFunction = function (stencilFunc) {
  11711. this._stencilState.stencilFunc = stencilFunc;
  11712. };
  11713. Engine.prototype.setStencilFunctionReference = function (reference) {
  11714. this._stencilState.stencilFuncRef = reference;
  11715. };
  11716. Engine.prototype.setStencilFunctionMask = function (mask) {
  11717. this._stencilState.stencilFuncMask = mask;
  11718. };
  11719. Engine.prototype.getStencilOperationFail = function () {
  11720. return this._stencilState.stencilOpStencilFail;
  11721. };
  11722. Engine.prototype.getStencilOperationDepthFail = function () {
  11723. return this._stencilState.stencilOpDepthFail;
  11724. };
  11725. Engine.prototype.getStencilOperationPass = function () {
  11726. return this._stencilState.stencilOpStencilDepthPass;
  11727. };
  11728. Engine.prototype.setStencilOperationFail = function (operation) {
  11729. this._stencilState.stencilOpStencilFail = operation;
  11730. };
  11731. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  11732. this._stencilState.stencilOpDepthFail = operation;
  11733. };
  11734. Engine.prototype.setStencilOperationPass = function (operation) {
  11735. this._stencilState.stencilOpStencilDepthPass = operation;
  11736. };
  11737. Engine.prototype.setDitheringState = function (value) {
  11738. if (value) {
  11739. this._gl.enable(this._gl.DITHER);
  11740. }
  11741. else {
  11742. this._gl.disable(this._gl.DITHER);
  11743. }
  11744. };
  11745. Engine.prototype.setRasterizerState = function (value) {
  11746. if (value) {
  11747. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  11748. }
  11749. else {
  11750. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  11751. }
  11752. };
  11753. /**
  11754. * stop executing a render loop function and remove it from the execution array
  11755. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  11756. */
  11757. Engine.prototype.stopRenderLoop = function (renderFunction) {
  11758. if (!renderFunction) {
  11759. this._activeRenderLoops = [];
  11760. return;
  11761. }
  11762. var index = this._activeRenderLoops.indexOf(renderFunction);
  11763. if (index >= 0) {
  11764. this._activeRenderLoops.splice(index, 1);
  11765. }
  11766. };
  11767. Engine.prototype._renderLoop = function () {
  11768. if (!this._contextWasLost) {
  11769. var shouldRender = true;
  11770. if (!this.renderEvenInBackground && this._windowIsBackground) {
  11771. shouldRender = false;
  11772. }
  11773. if (shouldRender) {
  11774. // Start new frame
  11775. this.beginFrame();
  11776. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  11777. var renderFunction = this._activeRenderLoops[index];
  11778. renderFunction();
  11779. }
  11780. // Present
  11781. this.endFrame();
  11782. }
  11783. }
  11784. if (this._activeRenderLoops.length > 0) {
  11785. // Register new frame
  11786. var requester = null;
  11787. if (this._vrDisplay && this._vrDisplay.isPresenting)
  11788. requester = this._vrDisplay;
  11789. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  11790. }
  11791. else {
  11792. this._renderingQueueLaunched = false;
  11793. }
  11794. };
  11795. /**
  11796. * Register and execute a render loop. The engine can have more than one render function.
  11797. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  11798. * @example
  11799. * engine.runRenderLoop(function () {
  11800. * scene.render()
  11801. * })
  11802. */
  11803. Engine.prototype.runRenderLoop = function (renderFunction) {
  11804. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  11805. return;
  11806. }
  11807. this._activeRenderLoops.push(renderFunction);
  11808. if (!this._renderingQueueLaunched) {
  11809. this._renderingQueueLaunched = true;
  11810. this._bindedRenderFunction = this._renderLoop.bind(this);
  11811. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  11812. }
  11813. };
  11814. /**
  11815. * Toggle full screen mode.
  11816. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  11817. * @param {any} options - an options object to be sent to the requestFullscreen function
  11818. */
  11819. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  11820. if (this.isFullscreen) {
  11821. BABYLON.Tools.ExitFullscreen();
  11822. }
  11823. else {
  11824. this._pointerLockRequested = requestPointerLock;
  11825. if (this._renderingCanvas) {
  11826. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  11827. }
  11828. }
  11829. };
  11830. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  11831. if (stencil === void 0) { stencil = false; }
  11832. this.applyStates();
  11833. var mode = 0;
  11834. if (backBuffer && color) {
  11835. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  11836. mode |= this._gl.COLOR_BUFFER_BIT;
  11837. }
  11838. if (depth) {
  11839. this._gl.clearDepth(1.0);
  11840. mode |= this._gl.DEPTH_BUFFER_BIT;
  11841. }
  11842. if (stencil) {
  11843. this._gl.clearStencil(0);
  11844. mode |= this._gl.STENCIL_BUFFER_BIT;
  11845. }
  11846. this._gl.clear(mode);
  11847. };
  11848. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  11849. var gl = this._gl;
  11850. // Save state
  11851. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  11852. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  11853. // Change state
  11854. gl.enable(gl.SCISSOR_TEST);
  11855. gl.scissor(x, y, width, height);
  11856. // Clear
  11857. this.clear(clearColor, true, true, true);
  11858. // Restore state
  11859. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  11860. if (curScissor === true) {
  11861. gl.enable(gl.SCISSOR_TEST);
  11862. }
  11863. else {
  11864. gl.disable(gl.SCISSOR_TEST);
  11865. }
  11866. };
  11867. /**
  11868. * Set the WebGL's viewport
  11869. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  11870. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  11871. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  11872. */
  11873. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  11874. var width = requiredWidth || this.getRenderWidth();
  11875. var height = requiredHeight || this.getRenderHeight();
  11876. var x = viewport.x || 0;
  11877. var y = viewport.y || 0;
  11878. this._cachedViewport = viewport;
  11879. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  11880. };
  11881. /**
  11882. * Directly set the WebGL Viewport
  11883. * The x, y, width & height are directly passed to the WebGL call
  11884. * @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.
  11885. */
  11886. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  11887. var currentViewport = this._cachedViewport;
  11888. this._cachedViewport = null;
  11889. this._gl.viewport(x, y, width, height);
  11890. return currentViewport;
  11891. };
  11892. Engine.prototype.beginFrame = function () {
  11893. this.onBeginFrameObservable.notifyObservers(this);
  11894. this._measureFps();
  11895. };
  11896. Engine.prototype.endFrame = function () {
  11897. //force a flush in case we are using a bad OS.
  11898. if (this._badOS) {
  11899. this.flushFramebuffer();
  11900. }
  11901. //submit frame to the vr device, if enabled
  11902. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  11903. // TODO: We should only submit the frame if we read frameData successfully.
  11904. this._vrDisplay.submitFrame();
  11905. }
  11906. this.onEndFrameObservable.notifyObservers(this);
  11907. };
  11908. /**
  11909. * resize the view according to the canvas' size.
  11910. * @example
  11911. * window.addEventListener("resize", function () {
  11912. * engine.resize();
  11913. * });
  11914. */
  11915. Engine.prototype.resize = function () {
  11916. // We're not resizing the size of the canvas while in VR mode & presenting
  11917. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  11918. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  11919. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  11920. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  11921. }
  11922. };
  11923. /**
  11924. * force a specific size of the canvas
  11925. * @param {number} width - the new canvas' width
  11926. * @param {number} height - the new canvas' height
  11927. */
  11928. Engine.prototype.setSize = function (width, height) {
  11929. if (!this._renderingCanvas) {
  11930. return;
  11931. }
  11932. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  11933. return;
  11934. }
  11935. this._renderingCanvas.width = width;
  11936. this._renderingCanvas.height = height;
  11937. for (var index = 0; index < this.scenes.length; index++) {
  11938. var scene = this.scenes[index];
  11939. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  11940. var cam = scene.cameras[camIndex];
  11941. cam._currentRenderId = 0;
  11942. }
  11943. }
  11944. if (this.onResizeObservable.hasObservers) {
  11945. this.onResizeObservable.notifyObservers(this);
  11946. }
  11947. };
  11948. // WebVR functions
  11949. Engine.prototype.isVRDevicePresent = function () {
  11950. return !!this._vrDisplay;
  11951. };
  11952. Engine.prototype.getVRDevice = function () {
  11953. return this._vrDisplay;
  11954. };
  11955. /**
  11956. * Initializes a webVR display and starts listening to display change events.
  11957. * The onVRDisplayChangedObservable will be notified upon these changes.
  11958. * @returns The onVRDisplayChangedObservable.
  11959. */
  11960. Engine.prototype.initWebVR = function () {
  11961. this.initWebVRAsync();
  11962. return this.onVRDisplayChangedObservable;
  11963. };
  11964. /**
  11965. * Initializes a webVR display and starts listening to display change events.
  11966. * The onVRDisplayChangedObservable will be notified upon these changes.
  11967. * @returns A promise containing a VRDisplay and if vr is supported.
  11968. */
  11969. Engine.prototype.initWebVRAsync = function () {
  11970. var _this = this;
  11971. var notifyObservers = function () {
  11972. var eventArgs = {
  11973. vrDisplay: _this._vrDisplay,
  11974. vrSupported: _this._vrSupported
  11975. };
  11976. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  11977. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  11978. };
  11979. if (!this._onVrDisplayConnect) {
  11980. this._onVrDisplayConnect = function (event) {
  11981. _this._vrDisplay = event.display;
  11982. notifyObservers();
  11983. };
  11984. this._onVrDisplayDisconnect = function () {
  11985. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  11986. _this._vrDisplay = undefined;
  11987. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  11988. notifyObservers();
  11989. };
  11990. this._onVrDisplayPresentChange = function () {
  11991. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  11992. };
  11993. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  11994. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  11995. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  11996. }
  11997. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  11998. this._webVRInitPromise.then(notifyObservers);
  11999. return this._webVRInitPromise;
  12000. };
  12001. Engine.prototype.enableVR = function () {
  12002. var _this = this;
  12003. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12004. var onResolved = function () {
  12005. _this.onVRRequestPresentComplete.notifyObservers(true);
  12006. _this._onVRFullScreenTriggered();
  12007. };
  12008. var onRejected = function () {
  12009. _this.onVRRequestPresentComplete.notifyObservers(false);
  12010. };
  12011. this.onVRRequestPresentStart.notifyObservers(this);
  12012. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12013. }
  12014. };
  12015. Engine.prototype.disableVR = function () {
  12016. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12017. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12018. }
  12019. };
  12020. Engine.prototype._getVRDisplaysAsync = function () {
  12021. var _this = this;
  12022. return new Promise(function (res, rej) {
  12023. if (navigator.getVRDisplays) {
  12024. navigator.getVRDisplays().then(function (devices) {
  12025. _this._vrSupported = true;
  12026. // note that devices may actually be an empty array. This is fine;
  12027. // we expect this._vrDisplay to be undefined in this case.
  12028. _this._vrDisplay = devices[0];
  12029. res({
  12030. vrDisplay: _this._vrDisplay,
  12031. vrSupported: _this._vrSupported
  12032. });
  12033. });
  12034. }
  12035. else {
  12036. _this._vrDisplay = undefined;
  12037. _this._vrSupported = false;
  12038. res({
  12039. vrDisplay: _this._vrDisplay,
  12040. vrSupported: _this._vrSupported
  12041. });
  12042. }
  12043. });
  12044. };
  12045. /**
  12046. * Binds the frame buffer to the specified texture.
  12047. * @param texture The texture to render to or null for the default canvas
  12048. * @param faceIndex The face of the texture to render to in case of cube texture
  12049. * @param requiredWidth The width of the target to render to
  12050. * @param requiredHeight The height of the target to render to
  12051. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12052. * @param depthStencilTexture The depth stencil texture to use to render
  12053. */
  12054. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  12055. if (this._currentRenderTarget) {
  12056. this.unBindFramebuffer(this._currentRenderTarget);
  12057. }
  12058. this._currentRenderTarget = texture;
  12059. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12060. var gl = this._gl;
  12061. if (texture.isCube) {
  12062. if (faceIndex === undefined) {
  12063. faceIndex = 0;
  12064. }
  12065. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  12066. if (depthStencilTexture) {
  12067. if (depthStencilTexture._generateStencilBuffer) {
  12068. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12069. }
  12070. else {
  12071. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12072. }
  12073. }
  12074. }
  12075. if (this._cachedViewport && !forceFullscreenViewport) {
  12076. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12077. }
  12078. else {
  12079. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  12080. }
  12081. this.wipeCaches();
  12082. };
  12083. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12084. if (this._currentFramebuffer !== framebuffer) {
  12085. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  12086. this._currentFramebuffer = framebuffer;
  12087. }
  12088. };
  12089. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  12090. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12091. this._currentRenderTarget = null;
  12092. // If MSAA, we need to bitblt back to main texture
  12093. var gl = this._gl;
  12094. if (texture._MSAAFramebuffer) {
  12095. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  12096. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  12097. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12098. }
  12099. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12100. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  12101. gl.generateMipmap(gl.TEXTURE_2D);
  12102. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12103. }
  12104. if (onBeforeUnbind) {
  12105. if (texture._MSAAFramebuffer) {
  12106. // Bind the correct framebuffer
  12107. this.bindUnboundFramebuffer(texture._framebuffer);
  12108. }
  12109. onBeforeUnbind();
  12110. }
  12111. this.bindUnboundFramebuffer(null);
  12112. };
  12113. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  12114. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  12115. this._currentRenderTarget = null;
  12116. // If MSAA, we need to bitblt back to main texture
  12117. var gl = this._gl;
  12118. if (textures[0]._MSAAFramebuffer) {
  12119. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  12120. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  12121. var attachments = textures[0]._attachments;
  12122. if (!attachments) {
  12123. attachments = new Array(textures.length);
  12124. textures[0]._attachments = attachments;
  12125. }
  12126. for (var i = 0; i < textures.length; i++) {
  12127. var texture = textures[i];
  12128. for (var j = 0; j < attachments.length; j++) {
  12129. attachments[j] = gl.NONE;
  12130. }
  12131. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12132. gl.readBuffer(attachments[i]);
  12133. gl.drawBuffers(attachments);
  12134. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  12135. }
  12136. for (var i = 0; i < attachments.length; i++) {
  12137. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  12138. }
  12139. gl.drawBuffers(attachments);
  12140. }
  12141. for (var i = 0; i < textures.length; i++) {
  12142. var texture = textures[i];
  12143. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  12144. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  12145. gl.generateMipmap(gl.TEXTURE_2D);
  12146. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  12147. }
  12148. }
  12149. if (onBeforeUnbind) {
  12150. if (textures[0]._MSAAFramebuffer) {
  12151. // Bind the correct framebuffer
  12152. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  12153. }
  12154. onBeforeUnbind();
  12155. }
  12156. this.bindUnboundFramebuffer(null);
  12157. };
  12158. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  12159. if (texture.generateMipMaps) {
  12160. var gl = this._gl;
  12161. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  12162. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  12163. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  12164. }
  12165. };
  12166. Engine.prototype.flushFramebuffer = function () {
  12167. this._gl.flush();
  12168. };
  12169. Engine.prototype.restoreDefaultFramebuffer = function () {
  12170. if (this._currentRenderTarget) {
  12171. this.unBindFramebuffer(this._currentRenderTarget);
  12172. }
  12173. else {
  12174. this.bindUnboundFramebuffer(null);
  12175. }
  12176. if (this._cachedViewport) {
  12177. this.setViewport(this._cachedViewport);
  12178. }
  12179. this.wipeCaches();
  12180. };
  12181. // UBOs
  12182. Engine.prototype.createUniformBuffer = function (elements) {
  12183. var ubo = this._gl.createBuffer();
  12184. if (!ubo) {
  12185. throw new Error("Unable to create uniform buffer");
  12186. }
  12187. this.bindUniformBuffer(ubo);
  12188. if (elements instanceof Float32Array) {
  12189. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  12190. }
  12191. else {
  12192. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  12193. }
  12194. this.bindUniformBuffer(null);
  12195. ubo.references = 1;
  12196. return ubo;
  12197. };
  12198. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  12199. var ubo = this._gl.createBuffer();
  12200. if (!ubo) {
  12201. throw new Error("Unable to create dynamic uniform buffer");
  12202. }
  12203. this.bindUniformBuffer(ubo);
  12204. if (elements instanceof Float32Array) {
  12205. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  12206. }
  12207. else {
  12208. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  12209. }
  12210. this.bindUniformBuffer(null);
  12211. ubo.references = 1;
  12212. return ubo;
  12213. };
  12214. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  12215. this.bindUniformBuffer(uniformBuffer);
  12216. if (offset === undefined) {
  12217. offset = 0;
  12218. }
  12219. if (count === undefined) {
  12220. if (elements instanceof Float32Array) {
  12221. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  12222. }
  12223. else {
  12224. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  12225. }
  12226. }
  12227. else {
  12228. if (elements instanceof Float32Array) {
  12229. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  12230. }
  12231. else {
  12232. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  12233. }
  12234. }
  12235. this.bindUniformBuffer(null);
  12236. };
  12237. // VBOs
  12238. Engine.prototype._resetVertexBufferBinding = function () {
  12239. this.bindArrayBuffer(null);
  12240. this._cachedVertexBuffers = null;
  12241. };
  12242. Engine.prototype.createVertexBuffer = function (vertices) {
  12243. var vbo = this._gl.createBuffer();
  12244. if (!vbo) {
  12245. throw new Error("Unable to create vertex buffer");
  12246. }
  12247. this.bindArrayBuffer(vbo);
  12248. if (vertices instanceof Float32Array) {
  12249. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  12250. }
  12251. else {
  12252. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  12253. }
  12254. this._resetVertexBufferBinding();
  12255. vbo.references = 1;
  12256. return vbo;
  12257. };
  12258. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  12259. var vbo = this._gl.createBuffer();
  12260. if (!vbo) {
  12261. throw new Error("Unable to create dynamic vertex buffer");
  12262. }
  12263. this.bindArrayBuffer(vbo);
  12264. if (vertices instanceof Float32Array) {
  12265. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  12266. }
  12267. else {
  12268. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  12269. }
  12270. this._resetVertexBufferBinding();
  12271. vbo.references = 1;
  12272. return vbo;
  12273. };
  12274. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  12275. if (offset === void 0) { offset = 0; }
  12276. // Force cache update
  12277. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  12278. this.bindIndexBuffer(indexBuffer);
  12279. var arrayBuffer;
  12280. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  12281. arrayBuffer = indices;
  12282. }
  12283. else {
  12284. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12285. }
  12286. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  12287. this._resetIndexBufferBinding();
  12288. };
  12289. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  12290. this.bindArrayBuffer(vertexBuffer);
  12291. if (offset === undefined) {
  12292. offset = 0;
  12293. }
  12294. if (count === undefined) {
  12295. if (vertices instanceof Float32Array) {
  12296. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  12297. }
  12298. else {
  12299. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  12300. }
  12301. }
  12302. else {
  12303. if (vertices instanceof Float32Array) {
  12304. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  12305. }
  12306. else {
  12307. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  12308. }
  12309. }
  12310. this._resetVertexBufferBinding();
  12311. };
  12312. Engine.prototype._resetIndexBufferBinding = function () {
  12313. this.bindIndexBuffer(null);
  12314. this._cachedIndexBuffer = null;
  12315. };
  12316. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  12317. var vbo = this._gl.createBuffer();
  12318. if (!vbo) {
  12319. throw new Error("Unable to create index buffer");
  12320. }
  12321. this.bindIndexBuffer(vbo);
  12322. // Check for 32 bits indices
  12323. var arrayBuffer;
  12324. var need32Bits = false;
  12325. if (indices instanceof Uint16Array) {
  12326. arrayBuffer = indices;
  12327. }
  12328. else {
  12329. //check 32 bit support
  12330. if (this._caps.uintIndices) {
  12331. if (indices instanceof Uint32Array) {
  12332. arrayBuffer = indices;
  12333. need32Bits = true;
  12334. }
  12335. else {
  12336. //number[] or Int32Array, check if 32 bit is necessary
  12337. for (var index = 0; index < indices.length; index++) {
  12338. if (indices[index] > 65535) {
  12339. need32Bits = true;
  12340. break;
  12341. }
  12342. }
  12343. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  12344. }
  12345. }
  12346. else {
  12347. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  12348. arrayBuffer = new Uint16Array(indices);
  12349. }
  12350. }
  12351. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  12352. this._resetIndexBufferBinding();
  12353. vbo.references = 1;
  12354. vbo.is32Bits = need32Bits;
  12355. return vbo;
  12356. };
  12357. Engine.prototype.bindArrayBuffer = function (buffer) {
  12358. if (!this._vaoRecordInProgress) {
  12359. this._unbindVertexArrayObject();
  12360. }
  12361. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  12362. };
  12363. Engine.prototype.bindUniformBuffer = function (buffer) {
  12364. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  12365. };
  12366. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  12367. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  12368. };
  12369. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  12370. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  12371. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  12372. };
  12373. ;
  12374. Engine.prototype.bindIndexBuffer = function (buffer) {
  12375. if (!this._vaoRecordInProgress) {
  12376. this._unbindVertexArrayObject();
  12377. }
  12378. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  12379. };
  12380. Engine.prototype.bindBuffer = function (buffer, target) {
  12381. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  12382. this._gl.bindBuffer(target, buffer);
  12383. this._currentBoundBuffer[target] = buffer;
  12384. }
  12385. };
  12386. Engine.prototype.updateArrayBuffer = function (data) {
  12387. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12388. };
  12389. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  12390. var pointer = this._currentBufferPointers[indx];
  12391. var changed = false;
  12392. if (!pointer.active) {
  12393. changed = true;
  12394. pointer.active = true;
  12395. pointer.index = indx;
  12396. pointer.size = size;
  12397. pointer.type = type;
  12398. pointer.normalized = normalized;
  12399. pointer.stride = stride;
  12400. pointer.offset = offset;
  12401. pointer.buffer = buffer;
  12402. }
  12403. else {
  12404. if (pointer.buffer !== buffer) {
  12405. pointer.buffer = buffer;
  12406. changed = true;
  12407. }
  12408. if (pointer.size !== size) {
  12409. pointer.size = size;
  12410. changed = true;
  12411. }
  12412. if (pointer.type !== type) {
  12413. pointer.type = type;
  12414. changed = true;
  12415. }
  12416. if (pointer.normalized !== normalized) {
  12417. pointer.normalized = normalized;
  12418. changed = true;
  12419. }
  12420. if (pointer.stride !== stride) {
  12421. pointer.stride = stride;
  12422. changed = true;
  12423. }
  12424. if (pointer.offset !== offset) {
  12425. pointer.offset = offset;
  12426. changed = true;
  12427. }
  12428. }
  12429. if (changed || this._vaoRecordInProgress) {
  12430. this.bindArrayBuffer(buffer);
  12431. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  12432. }
  12433. };
  12434. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  12435. if (indexBuffer == null) {
  12436. return;
  12437. }
  12438. if (this._cachedIndexBuffer !== indexBuffer) {
  12439. this._cachedIndexBuffer = indexBuffer;
  12440. this.bindIndexBuffer(indexBuffer);
  12441. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  12442. }
  12443. };
  12444. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  12445. var attributes = effect.getAttributesNames();
  12446. if (!this._vaoRecordInProgress) {
  12447. this._unbindVertexArrayObject();
  12448. }
  12449. this.unbindAllAttributes();
  12450. for (var index = 0; index < attributes.length; index++) {
  12451. var order = effect.getAttributeLocation(index);
  12452. if (order >= 0) {
  12453. var vertexBuffer = vertexBuffers[attributes[index]];
  12454. if (!vertexBuffer) {
  12455. continue;
  12456. }
  12457. this._gl.enableVertexAttribArray(order);
  12458. if (!this._vaoRecordInProgress) {
  12459. this._vertexAttribArraysEnabled[order] = true;
  12460. }
  12461. var buffer = vertexBuffer.getBuffer();
  12462. if (buffer) {
  12463. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  12464. if (vertexBuffer.getIsInstanced()) {
  12465. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  12466. if (!this._vaoRecordInProgress) {
  12467. this._currentInstanceLocations.push(order);
  12468. this._currentInstanceBuffers.push(buffer);
  12469. }
  12470. }
  12471. }
  12472. }
  12473. }
  12474. };
  12475. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  12476. var vao = this._gl.createVertexArray();
  12477. this._vaoRecordInProgress = true;
  12478. this._gl.bindVertexArray(vao);
  12479. this._mustWipeVertexAttributes = true;
  12480. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12481. this.bindIndexBuffer(indexBuffer);
  12482. this._vaoRecordInProgress = false;
  12483. this._gl.bindVertexArray(null);
  12484. return vao;
  12485. };
  12486. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  12487. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  12488. this._cachedVertexArrayObject = vertexArrayObject;
  12489. this._gl.bindVertexArray(vertexArrayObject);
  12490. this._cachedVertexBuffers = null;
  12491. this._cachedIndexBuffer = null;
  12492. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  12493. this._mustWipeVertexAttributes = true;
  12494. }
  12495. };
  12496. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  12497. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  12498. this._cachedVertexBuffers = vertexBuffer;
  12499. this._cachedEffectForVertexBuffers = effect;
  12500. var attributesCount = effect.getAttributesCount();
  12501. this._unbindVertexArrayObject();
  12502. this.unbindAllAttributes();
  12503. var offset = 0;
  12504. for (var index = 0; index < attributesCount; index++) {
  12505. if (index < vertexDeclaration.length) {
  12506. var order = effect.getAttributeLocation(index);
  12507. if (order >= 0) {
  12508. this._gl.enableVertexAttribArray(order);
  12509. this._vertexAttribArraysEnabled[order] = true;
  12510. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  12511. }
  12512. offset += vertexDeclaration[index] * 4;
  12513. }
  12514. }
  12515. }
  12516. this._bindIndexBufferWithCache(indexBuffer);
  12517. };
  12518. Engine.prototype._unbindVertexArrayObject = function () {
  12519. if (!this._cachedVertexArrayObject) {
  12520. return;
  12521. }
  12522. this._cachedVertexArrayObject = null;
  12523. this._gl.bindVertexArray(null);
  12524. };
  12525. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  12526. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  12527. this._cachedVertexBuffers = vertexBuffers;
  12528. this._cachedEffectForVertexBuffers = effect;
  12529. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  12530. }
  12531. this._bindIndexBufferWithCache(indexBuffer);
  12532. };
  12533. Engine.prototype.unbindInstanceAttributes = function () {
  12534. var boundBuffer;
  12535. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  12536. var instancesBuffer = this._currentInstanceBuffers[i];
  12537. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  12538. boundBuffer = instancesBuffer;
  12539. this.bindArrayBuffer(instancesBuffer);
  12540. }
  12541. var offsetLocation = this._currentInstanceLocations[i];
  12542. this._gl.vertexAttribDivisor(offsetLocation, 0);
  12543. }
  12544. this._currentInstanceBuffers.length = 0;
  12545. this._currentInstanceLocations.length = 0;
  12546. };
  12547. Engine.prototype.releaseVertexArrayObject = function (vao) {
  12548. this._gl.deleteVertexArray(vao);
  12549. };
  12550. Engine.prototype._releaseBuffer = function (buffer) {
  12551. buffer.references--;
  12552. if (buffer.references === 0) {
  12553. this._gl.deleteBuffer(buffer);
  12554. return true;
  12555. }
  12556. return false;
  12557. };
  12558. Engine.prototype.createInstancesBuffer = function (capacity) {
  12559. var buffer = this._gl.createBuffer();
  12560. if (!buffer) {
  12561. throw new Error("Unable to create instance buffer");
  12562. }
  12563. buffer.capacity = capacity;
  12564. this.bindArrayBuffer(buffer);
  12565. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  12566. return buffer;
  12567. };
  12568. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  12569. this._gl.deleteBuffer(buffer);
  12570. };
  12571. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  12572. this.bindArrayBuffer(instancesBuffer);
  12573. if (data) {
  12574. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  12575. }
  12576. if (offsetLocations[0].index !== undefined) {
  12577. var stride = 0;
  12578. for (var i = 0; i < offsetLocations.length; i++) {
  12579. var ai = offsetLocations[i];
  12580. stride += ai.attributeSize * 4;
  12581. }
  12582. for (var i = 0; i < offsetLocations.length; i++) {
  12583. var ai = offsetLocations[i];
  12584. if (!this._vertexAttribArraysEnabled[ai.index]) {
  12585. this._gl.enableVertexAttribArray(ai.index);
  12586. this._vertexAttribArraysEnabled[ai.index] = true;
  12587. }
  12588. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  12589. this._gl.vertexAttribDivisor(ai.index, 1);
  12590. this._currentInstanceLocations.push(ai.index);
  12591. this._currentInstanceBuffers.push(instancesBuffer);
  12592. }
  12593. }
  12594. else {
  12595. for (var index = 0; index < 4; index++) {
  12596. var offsetLocation = offsetLocations[index];
  12597. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  12598. this._gl.enableVertexAttribArray(offsetLocation);
  12599. this._vertexAttribArraysEnabled[offsetLocation] = true;
  12600. }
  12601. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  12602. this._gl.vertexAttribDivisor(offsetLocation, 1);
  12603. this._currentInstanceLocations.push(offsetLocation);
  12604. this._currentInstanceBuffers.push(instancesBuffer);
  12605. }
  12606. }
  12607. };
  12608. Engine.prototype.applyStates = function () {
  12609. this._depthCullingState.apply(this._gl);
  12610. this._stencilState.apply(this._gl);
  12611. this._alphaState.apply(this._gl);
  12612. };
  12613. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  12614. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  12615. };
  12616. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  12617. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  12618. };
  12619. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  12620. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  12621. };
  12622. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  12623. // Apply states
  12624. this.applyStates();
  12625. this._drawCalls.addCount(1, false);
  12626. // Render
  12627. var drawMode = this._drawMode(fillMode);
  12628. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  12629. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  12630. if (instancesCount) {
  12631. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  12632. }
  12633. else {
  12634. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  12635. }
  12636. };
  12637. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  12638. // Apply states
  12639. this.applyStates();
  12640. this._drawCalls.addCount(1, false);
  12641. var drawMode = this._drawMode(fillMode);
  12642. if (instancesCount) {
  12643. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  12644. }
  12645. else {
  12646. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  12647. }
  12648. };
  12649. Engine.prototype._drawMode = function (fillMode) {
  12650. switch (fillMode) {
  12651. // Triangle views
  12652. case BABYLON.Material.TriangleFillMode:
  12653. return this._gl.TRIANGLES;
  12654. case BABYLON.Material.PointFillMode:
  12655. return this._gl.POINTS;
  12656. case BABYLON.Material.WireFrameFillMode:
  12657. return this._gl.LINES;
  12658. // Draw modes
  12659. case BABYLON.Material.PointListDrawMode:
  12660. return this._gl.POINTS;
  12661. case BABYLON.Material.LineListDrawMode:
  12662. return this._gl.LINES;
  12663. case BABYLON.Material.LineLoopDrawMode:
  12664. return this._gl.LINE_LOOP;
  12665. case BABYLON.Material.LineStripDrawMode:
  12666. return this._gl.LINE_STRIP;
  12667. case BABYLON.Material.TriangleStripDrawMode:
  12668. return this._gl.TRIANGLE_STRIP;
  12669. case BABYLON.Material.TriangleFanDrawMode:
  12670. return this._gl.TRIANGLE_FAN;
  12671. default:
  12672. return this._gl.TRIANGLES;
  12673. }
  12674. };
  12675. // Shaders
  12676. Engine.prototype._releaseEffect = function (effect) {
  12677. if (this._compiledEffects[effect._key]) {
  12678. delete this._compiledEffects[effect._key];
  12679. this._deleteProgram(effect.getProgram());
  12680. }
  12681. };
  12682. Engine.prototype._deleteProgram = function (program) {
  12683. if (program) {
  12684. program.__SPECTOR_rebuildProgram = null;
  12685. if (program.transformFeedback) {
  12686. this.deleteTransformFeedback(program.transformFeedback);
  12687. program.transformFeedback = null;
  12688. }
  12689. this._gl.deleteProgram(program);
  12690. }
  12691. };
  12692. /**
  12693. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  12694. * @param samplers An array of string used to represent textures
  12695. */
  12696. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  12697. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  12698. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  12699. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  12700. if (this._compiledEffects[name]) {
  12701. var compiledEffect = this._compiledEffects[name];
  12702. if (onCompiled && compiledEffect.isReady()) {
  12703. onCompiled(compiledEffect);
  12704. }
  12705. return compiledEffect;
  12706. }
  12707. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  12708. effect._key = name;
  12709. this._compiledEffects[name] = effect;
  12710. return effect;
  12711. };
  12712. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  12713. if (uniformsNames === void 0) { uniformsNames = []; }
  12714. if (samplers === void 0) { samplers = []; }
  12715. if (defines === void 0) { defines = ""; }
  12716. return this.createEffect({
  12717. vertex: "particles",
  12718. fragmentElement: fragmentName
  12719. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  12720. };
  12721. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  12722. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12723. context = context || this._gl;
  12724. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  12725. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  12726. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12727. };
  12728. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  12729. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12730. context = context || this._gl;
  12731. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  12732. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  12733. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  12734. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  12735. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  12736. this.onAfterShaderCompilationObservable.notifyObservers(this);
  12737. return program;
  12738. };
  12739. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  12740. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  12741. var shaderProgram = context.createProgram();
  12742. if (!shaderProgram) {
  12743. throw new Error("Unable to create program");
  12744. }
  12745. context.attachShader(shaderProgram, vertexShader);
  12746. context.attachShader(shaderProgram, fragmentShader);
  12747. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12748. var transformFeedback = this.createTransformFeedback();
  12749. this.bindTransformFeedback(transformFeedback);
  12750. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  12751. shaderProgram.transformFeedback = transformFeedback;
  12752. }
  12753. context.linkProgram(shaderProgram);
  12754. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  12755. this.bindTransformFeedback(null);
  12756. }
  12757. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  12758. if (!linked) {
  12759. context.validateProgram(shaderProgram);
  12760. var error = context.getProgramInfoLog(shaderProgram);
  12761. if (error) {
  12762. throw new Error(error);
  12763. }
  12764. }
  12765. context.deleteShader(vertexShader);
  12766. context.deleteShader(fragmentShader);
  12767. return shaderProgram;
  12768. };
  12769. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  12770. var results = new Array();
  12771. for (var index = 0; index < uniformsNames.length; index++) {
  12772. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  12773. }
  12774. return results;
  12775. };
  12776. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  12777. var results = [];
  12778. for (var index = 0; index < attributesNames.length; index++) {
  12779. try {
  12780. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  12781. }
  12782. catch (e) {
  12783. results.push(-1);
  12784. }
  12785. }
  12786. return results;
  12787. };
  12788. Engine.prototype.enableEffect = function (effect) {
  12789. if (!effect) {
  12790. return;
  12791. }
  12792. // Use program
  12793. this.bindSamplers(effect);
  12794. this._currentEffect = effect;
  12795. if (effect.onBind) {
  12796. effect.onBind(effect);
  12797. }
  12798. effect.onBindObservable.notifyObservers(effect);
  12799. };
  12800. Engine.prototype.setIntArray = function (uniform, array) {
  12801. if (!uniform)
  12802. return;
  12803. this._gl.uniform1iv(uniform, array);
  12804. };
  12805. Engine.prototype.setIntArray2 = function (uniform, array) {
  12806. if (!uniform || array.length % 2 !== 0)
  12807. return;
  12808. this._gl.uniform2iv(uniform, array);
  12809. };
  12810. Engine.prototype.setIntArray3 = function (uniform, array) {
  12811. if (!uniform || array.length % 3 !== 0)
  12812. return;
  12813. this._gl.uniform3iv(uniform, array);
  12814. };
  12815. Engine.prototype.setIntArray4 = function (uniform, array) {
  12816. if (!uniform || array.length % 4 !== 0)
  12817. return;
  12818. this._gl.uniform4iv(uniform, array);
  12819. };
  12820. Engine.prototype.setFloatArray = function (uniform, array) {
  12821. if (!uniform)
  12822. return;
  12823. this._gl.uniform1fv(uniform, array);
  12824. };
  12825. Engine.prototype.setFloatArray2 = function (uniform, array) {
  12826. if (!uniform || array.length % 2 !== 0)
  12827. return;
  12828. this._gl.uniform2fv(uniform, array);
  12829. };
  12830. Engine.prototype.setFloatArray3 = function (uniform, array) {
  12831. if (!uniform || array.length % 3 !== 0)
  12832. return;
  12833. this._gl.uniform3fv(uniform, array);
  12834. };
  12835. Engine.prototype.setFloatArray4 = function (uniform, array) {
  12836. if (!uniform || array.length % 4 !== 0)
  12837. return;
  12838. this._gl.uniform4fv(uniform, array);
  12839. };
  12840. Engine.prototype.setArray = function (uniform, array) {
  12841. if (!uniform)
  12842. return;
  12843. this._gl.uniform1fv(uniform, array);
  12844. };
  12845. Engine.prototype.setArray2 = function (uniform, array) {
  12846. if (!uniform || array.length % 2 !== 0)
  12847. return;
  12848. this._gl.uniform2fv(uniform, array);
  12849. };
  12850. Engine.prototype.setArray3 = function (uniform, array) {
  12851. if (!uniform || array.length % 3 !== 0)
  12852. return;
  12853. this._gl.uniform3fv(uniform, array);
  12854. };
  12855. Engine.prototype.setArray4 = function (uniform, array) {
  12856. if (!uniform || array.length % 4 !== 0)
  12857. return;
  12858. this._gl.uniform4fv(uniform, array);
  12859. };
  12860. Engine.prototype.setMatrices = function (uniform, matrices) {
  12861. if (!uniform)
  12862. return;
  12863. this._gl.uniformMatrix4fv(uniform, false, matrices);
  12864. };
  12865. Engine.prototype.setMatrix = function (uniform, matrix) {
  12866. if (!uniform)
  12867. return;
  12868. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  12869. };
  12870. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  12871. if (!uniform)
  12872. return;
  12873. this._gl.uniformMatrix3fv(uniform, false, matrix);
  12874. };
  12875. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  12876. if (!uniform)
  12877. return;
  12878. this._gl.uniformMatrix2fv(uniform, false, matrix);
  12879. };
  12880. Engine.prototype.setInt = function (uniform, value) {
  12881. if (!uniform)
  12882. return;
  12883. this._gl.uniform1i(uniform, value);
  12884. };
  12885. Engine.prototype.setFloat = function (uniform, value) {
  12886. if (!uniform)
  12887. return;
  12888. this._gl.uniform1f(uniform, value);
  12889. };
  12890. Engine.prototype.setFloat2 = function (uniform, x, y) {
  12891. if (!uniform)
  12892. return;
  12893. this._gl.uniform2f(uniform, x, y);
  12894. };
  12895. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  12896. if (!uniform)
  12897. return;
  12898. this._gl.uniform3f(uniform, x, y, z);
  12899. };
  12900. Engine.prototype.setBool = function (uniform, bool) {
  12901. if (!uniform)
  12902. return;
  12903. this._gl.uniform1i(uniform, bool);
  12904. };
  12905. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  12906. if (!uniform)
  12907. return;
  12908. this._gl.uniform4f(uniform, x, y, z, w);
  12909. };
  12910. Engine.prototype.setColor3 = function (uniform, color3) {
  12911. if (!uniform)
  12912. return;
  12913. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  12914. };
  12915. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  12916. if (!uniform)
  12917. return;
  12918. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  12919. };
  12920. /**
  12921. * Sets a Color4 on a uniform variable
  12922. * @param uniform defines the uniform location
  12923. * @param color4 defines the value to be set
  12924. */
  12925. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  12926. if (!uniform)
  12927. return;
  12928. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  12929. };
  12930. // States
  12931. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  12932. if (zOffset === void 0) { zOffset = 0; }
  12933. if (reverseSide === void 0) { reverseSide = false; }
  12934. // Culling
  12935. if (this._depthCullingState.cull !== culling || force) {
  12936. this._depthCullingState.cull = culling;
  12937. }
  12938. // Cull face
  12939. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  12940. if (this._depthCullingState.cullFace !== cullFace || force) {
  12941. this._depthCullingState.cullFace = cullFace;
  12942. }
  12943. // Z offset
  12944. this.setZOffset(zOffset);
  12945. // Front face
  12946. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  12947. if (this._depthCullingState.frontFace !== frontFace || force) {
  12948. this._depthCullingState.frontFace = frontFace;
  12949. }
  12950. };
  12951. Engine.prototype.setZOffset = function (value) {
  12952. this._depthCullingState.zOffset = value;
  12953. };
  12954. Engine.prototype.getZOffset = function () {
  12955. return this._depthCullingState.zOffset;
  12956. };
  12957. Engine.prototype.setDepthBuffer = function (enable) {
  12958. this._depthCullingState.depthTest = enable;
  12959. };
  12960. Engine.prototype.getDepthWrite = function () {
  12961. return this._depthCullingState.depthMask;
  12962. };
  12963. Engine.prototype.setDepthWrite = function (enable) {
  12964. this._depthCullingState.depthMask = enable;
  12965. };
  12966. Engine.prototype.setColorWrite = function (enable) {
  12967. this._gl.colorMask(enable, enable, enable, enable);
  12968. this._colorWrite = enable;
  12969. };
  12970. Engine.prototype.getColorWrite = function () {
  12971. return this._colorWrite;
  12972. };
  12973. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  12974. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  12975. };
  12976. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  12977. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  12978. if (this._alphaMode === mode) {
  12979. return;
  12980. }
  12981. switch (mode) {
  12982. case Engine.ALPHA_DISABLE:
  12983. this._alphaState.alphaBlend = false;
  12984. break;
  12985. case Engine.ALPHA_PREMULTIPLIED:
  12986. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12987. this._alphaState.alphaBlend = true;
  12988. break;
  12989. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  12990. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  12991. this._alphaState.alphaBlend = true;
  12992. break;
  12993. case Engine.ALPHA_COMBINE:
  12994. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  12995. this._alphaState.alphaBlend = true;
  12996. break;
  12997. case Engine.ALPHA_ONEONE:
  12998. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  12999. this._alphaState.alphaBlend = true;
  13000. break;
  13001. case Engine.ALPHA_ADD:
  13002. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  13003. this._alphaState.alphaBlend = true;
  13004. break;
  13005. case Engine.ALPHA_SUBTRACT:
  13006. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  13007. this._alphaState.alphaBlend = true;
  13008. break;
  13009. case Engine.ALPHA_MULTIPLY:
  13010. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  13011. this._alphaState.alphaBlend = true;
  13012. break;
  13013. case Engine.ALPHA_MAXIMIZED:
  13014. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  13015. this._alphaState.alphaBlend = true;
  13016. break;
  13017. case Engine.ALPHA_INTERPOLATE:
  13018. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  13019. this._alphaState.alphaBlend = true;
  13020. break;
  13021. case Engine.ALPHA_SCREENMODE:
  13022. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  13023. this._alphaState.alphaBlend = true;
  13024. break;
  13025. }
  13026. if (!noDepthWriteChange) {
  13027. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  13028. }
  13029. this._alphaMode = mode;
  13030. };
  13031. Engine.prototype.getAlphaMode = function () {
  13032. return this._alphaMode;
  13033. };
  13034. // Textures
  13035. Engine.prototype.wipeCaches = function (bruteForce) {
  13036. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  13037. return;
  13038. }
  13039. this._currentEffect = null;
  13040. // 6/8/2017: deltakosh: Should not be required anymore.
  13041. // This message is then mostly for the future myself who will scream out loud when seeing that it was actually required :)
  13042. if (bruteForce) {
  13043. this.resetTextureCache();
  13044. this._currentProgram = null;
  13045. this._stencilState.reset();
  13046. this._depthCullingState.reset();
  13047. this.setDepthFunctionToLessOrEqual();
  13048. this._alphaState.reset();
  13049. }
  13050. this._resetVertexBufferBinding();
  13051. this._cachedIndexBuffer = null;
  13052. this._cachedEffectForVertexBuffers = null;
  13053. this._unbindVertexArrayObject();
  13054. this.bindIndexBuffer(null);
  13055. };
  13056. /**
  13057. * Set the compressed texture format to use, based on the formats you have, and the formats
  13058. * supported by the hardware / browser.
  13059. *
  13060. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  13061. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  13062. * to API arguments needed to compressed textures. This puts the burden on the container
  13063. * generator to house the arcane code for determining these for current & future formats.
  13064. *
  13065. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  13066. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  13067. *
  13068. * Note: The result of this call is not taken into account when a texture is base64.
  13069. *
  13070. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  13071. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  13072. *
  13073. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  13074. * @returns The extension selected.
  13075. */
  13076. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  13077. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  13078. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  13079. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  13080. return this._textureFormatInUse = this._texturesSupported[i];
  13081. }
  13082. }
  13083. }
  13084. // actively set format to nothing, to allow this to be called more than once
  13085. // and possibly fail the 2nd time
  13086. this._textureFormatInUse = null;
  13087. return null;
  13088. };
  13089. Engine.prototype._createTexture = function () {
  13090. var texture = this._gl.createTexture();
  13091. if (!texture) {
  13092. throw new Error("Unable to create texture");
  13093. }
  13094. return texture;
  13095. };
  13096. /**
  13097. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  13098. * @param {string} urlArg- This contains one of the following:
  13099. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  13100. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  13101. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  13102. *
  13103. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  13104. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  13105. * @param {Scene} scene- Needed for loading to the correct scene.
  13106. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  13107. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  13108. * @param {callback} onError- Optional callback to be called upon failure.
  13109. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  13110. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  13111. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  13112. *
  13113. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  13114. */
  13115. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  13116. var _this = this;
  13117. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  13118. if (onLoad === void 0) { onLoad = null; }
  13119. if (onError === void 0) { onError = null; }
  13120. if (buffer === void 0) { buffer = null; }
  13121. if (fallBack === void 0) { fallBack = null; }
  13122. if (format === void 0) { format = null; }
  13123. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  13124. var fromData = url.substr(0, 5) === "data:";
  13125. var fromBlob = url.substr(0, 5) === "blob:";
  13126. var isBase64 = fromData && url.indexOf("base64") !== -1;
  13127. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  13128. // establish the file extension, if possible
  13129. var lastDot = url.lastIndexOf('.');
  13130. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  13131. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  13132. var isTGA = (extension.indexOf(".tga") === 0);
  13133. // determine if a ktx file should be substituted
  13134. var isKTX = false;
  13135. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  13136. url = url.substring(0, lastDot) + this._textureFormatInUse;
  13137. isKTX = true;
  13138. }
  13139. if (scene) {
  13140. scene._addPendingData(texture);
  13141. }
  13142. texture.url = url;
  13143. texture.generateMipMaps = !noMipmap;
  13144. texture.samplingMode = samplingMode;
  13145. texture.invertY = invertY;
  13146. if (!this._doNotHandleContextLost) {
  13147. // Keep a link to the buffer only if we plan to handle context lost
  13148. texture._buffer = buffer;
  13149. }
  13150. var onLoadObserver = null;
  13151. if (onLoad && !fallBack) {
  13152. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  13153. }
  13154. if (!fallBack)
  13155. this._internalTexturesCache.push(texture);
  13156. var onerror = function (message, exception) {
  13157. if (scene) {
  13158. scene._removePendingData(texture);
  13159. }
  13160. if (onLoadObserver) {
  13161. texture.onLoadedObservable.remove(onLoadObserver);
  13162. }
  13163. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  13164. if (isKTX) {
  13165. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  13166. }
  13167. else if (BABYLON.Tools.UseFallbackTexture) {
  13168. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  13169. }
  13170. if (onError) {
  13171. onError(message || "Unknown error", exception);
  13172. }
  13173. };
  13174. var callback = null;
  13175. // processing for non-image formats
  13176. if (isKTX || isTGA || isDDS) {
  13177. if (isKTX) {
  13178. callback = function (data) {
  13179. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  13180. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  13181. ktx.uploadLevels(_this._gl, !noMipmap);
  13182. return false;
  13183. }, samplingMode);
  13184. };
  13185. }
  13186. else if (isTGA) {
  13187. callback = function (arrayBuffer) {
  13188. var data = new Uint8Array(arrayBuffer);
  13189. var header = BABYLON.TGATools.GetTGAHeader(data);
  13190. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  13191. BABYLON.TGATools.UploadContent(_this._gl, data);
  13192. return false;
  13193. }, samplingMode);
  13194. };
  13195. }
  13196. else if (isDDS) {
  13197. callback = function (data) {
  13198. var info = BABYLON.DDSTools.GetDDSInfo(data);
  13199. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  13200. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  13201. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  13202. return false;
  13203. }, samplingMode);
  13204. };
  13205. }
  13206. if (!buffer) {
  13207. this._loadFile(url, function (data) {
  13208. if (callback) {
  13209. callback(data);
  13210. }
  13211. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  13212. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  13213. });
  13214. }
  13215. else {
  13216. if (callback) {
  13217. callback(buffer);
  13218. }
  13219. }
  13220. // image format processing
  13221. }
  13222. else {
  13223. var onload = function (img) {
  13224. if (fromBlob && !_this._doNotHandleContextLost) {
  13225. // We need to store the image if we need to rebuild the texture
  13226. // in case of a webgl context lost
  13227. texture._buffer = img;
  13228. }
  13229. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  13230. var gl = _this._gl;
  13231. var isPot = (img.width === potWidth && img.height === potHeight);
  13232. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  13233. if (isPot) {
  13234. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13235. return false;
  13236. }
  13237. // Using shaders to rescale because canvas.drawImage is lossy
  13238. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  13239. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  13240. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  13241. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  13242. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  13243. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13244. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13245. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  13246. _this._releaseTexture(source);
  13247. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13248. continuationCallback();
  13249. });
  13250. return true;
  13251. }, samplingMode);
  13252. };
  13253. if (!fromData || isBase64)
  13254. if (buffer instanceof HTMLImageElement) {
  13255. onload(buffer);
  13256. }
  13257. else {
  13258. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  13259. }
  13260. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  13261. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  13262. else
  13263. onload(buffer);
  13264. }
  13265. return texture;
  13266. };
  13267. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  13268. var _this = this;
  13269. var rtt = this.createRenderTargetTexture({
  13270. width: destination.width,
  13271. height: destination.height,
  13272. }, {
  13273. generateMipMaps: false,
  13274. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  13275. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  13276. generateDepthBuffer: false,
  13277. generateStencilBuffer: false
  13278. });
  13279. if (!this._rescalePostProcess) {
  13280. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  13281. }
  13282. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  13283. _this._rescalePostProcess.onApply = function (effect) {
  13284. effect._bindTexture("textureSampler", source);
  13285. };
  13286. var hostingScene = scene;
  13287. if (!hostingScene) {
  13288. hostingScene = _this.scenes[_this.scenes.length - 1];
  13289. }
  13290. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  13291. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  13292. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  13293. _this.unBindFramebuffer(rtt);
  13294. _this._releaseTexture(rtt);
  13295. if (onComplete) {
  13296. onComplete();
  13297. }
  13298. });
  13299. };
  13300. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  13301. if (compression === void 0) { compression = null; }
  13302. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13303. if (!texture) {
  13304. return;
  13305. }
  13306. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  13307. var internalFormat = this._getInternalFormat(format);
  13308. var textureType = this._getWebGLTextureType(type);
  13309. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13310. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  13311. if (!this._doNotHandleContextLost) {
  13312. texture._bufferView = data;
  13313. texture.format = format;
  13314. texture.type = type;
  13315. texture.invertY = invertY;
  13316. texture._compression = compression;
  13317. }
  13318. if (texture.width % 4 !== 0) {
  13319. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  13320. }
  13321. if (compression && data) {
  13322. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  13323. }
  13324. else {
  13325. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  13326. }
  13327. if (texture.generateMipMaps) {
  13328. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13329. }
  13330. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13331. // this.resetTextureCache();
  13332. texture.isReady = true;
  13333. };
  13334. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  13335. if (compression === void 0) { compression = null; }
  13336. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  13337. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  13338. texture.baseWidth = width;
  13339. texture.baseHeight = height;
  13340. texture.width = width;
  13341. texture.height = height;
  13342. texture.format = format;
  13343. texture.generateMipMaps = generateMipMaps;
  13344. texture.samplingMode = samplingMode;
  13345. texture.invertY = invertY;
  13346. texture._compression = compression;
  13347. texture.type = type;
  13348. if (!this._doNotHandleContextLost) {
  13349. texture._bufferView = data;
  13350. }
  13351. this.updateRawTexture(texture, data, format, invertY, compression, type);
  13352. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13353. // Filters
  13354. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  13355. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13356. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13357. if (generateMipMaps) {
  13358. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13359. }
  13360. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13361. this._internalTexturesCache.push(texture);
  13362. return texture;
  13363. };
  13364. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  13365. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  13366. texture.baseWidth = width;
  13367. texture.baseHeight = height;
  13368. if (generateMipMaps) {
  13369. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  13370. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  13371. }
  13372. // this.resetTextureCache();
  13373. texture.width = width;
  13374. texture.height = height;
  13375. texture.isReady = false;
  13376. texture.generateMipMaps = generateMipMaps;
  13377. texture.samplingMode = samplingMode;
  13378. this.updateTextureSamplingMode(samplingMode, texture);
  13379. this._internalTexturesCache.push(texture);
  13380. return texture;
  13381. };
  13382. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  13383. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  13384. if (texture.isCube) {
  13385. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13386. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13387. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13388. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13389. }
  13390. else if (texture.is3D) {
  13391. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  13392. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13393. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13394. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  13395. }
  13396. else {
  13397. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13398. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  13399. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  13400. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13401. }
  13402. texture.samplingMode = samplingMode;
  13403. };
  13404. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  13405. if (premulAlpha === void 0) { premulAlpha = false; }
  13406. if (!texture) {
  13407. return;
  13408. }
  13409. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13410. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  13411. if (premulAlpha) {
  13412. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  13413. }
  13414. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  13415. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  13416. if (texture.generateMipMaps) {
  13417. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13418. }
  13419. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13420. if (premulAlpha) {
  13421. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  13422. }
  13423. texture.isReady = true;
  13424. };
  13425. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  13426. if (!texture || texture._isDisabled) {
  13427. return;
  13428. }
  13429. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13430. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  13431. try {
  13432. // Testing video texture support
  13433. if (this._videoTextureSupported === undefined) {
  13434. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13435. if (this._gl.getError() !== 0) {
  13436. this._videoTextureSupported = false;
  13437. }
  13438. else {
  13439. this._videoTextureSupported = true;
  13440. }
  13441. }
  13442. // Copy video through the current working canvas if video texture is not supported
  13443. if (!this._videoTextureSupported) {
  13444. if (!texture._workingCanvas) {
  13445. texture._workingCanvas = document.createElement("canvas");
  13446. var context = texture._workingCanvas.getContext("2d");
  13447. if (!context) {
  13448. throw new Error("Unable to get 2d context");
  13449. }
  13450. texture._workingContext = context;
  13451. texture._workingCanvas.width = texture.width;
  13452. texture._workingCanvas.height = texture.height;
  13453. }
  13454. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  13455. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  13456. }
  13457. else {
  13458. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  13459. }
  13460. if (texture.generateMipMaps) {
  13461. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13462. }
  13463. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13464. // this.resetTextureCache();
  13465. texture.isReady = true;
  13466. }
  13467. catch (ex) {
  13468. // Something unexpected
  13469. // Let's disable the texture
  13470. texture._isDisabled = true;
  13471. }
  13472. };
  13473. /**
  13474. * Updates a depth texture Comparison Mode and Function.
  13475. * If the comparison Function is equal to 0, the mode will be set to none.
  13476. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  13477. * @param texture The texture to set the comparison function for
  13478. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  13479. */
  13480. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  13481. if (this.webGLVersion === 1) {
  13482. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  13483. return;
  13484. }
  13485. var gl = this._gl;
  13486. if (texture.isCube) {
  13487. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  13488. if (comparisonFunction === 0) {
  13489. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13490. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13491. }
  13492. else {
  13493. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13494. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13495. }
  13496. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  13497. }
  13498. else {
  13499. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  13500. if (comparisonFunction === 0) {
  13501. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13502. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13503. }
  13504. else {
  13505. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13506. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13507. }
  13508. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  13509. }
  13510. texture._comparisonFunction = comparisonFunction;
  13511. };
  13512. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  13513. var width = size.width || size;
  13514. var height = size.height || size;
  13515. internalTexture.baseWidth = width;
  13516. internalTexture.baseHeight = height;
  13517. internalTexture.width = width;
  13518. internalTexture.height = height;
  13519. internalTexture.isReady = true;
  13520. internalTexture.samples = 1;
  13521. internalTexture.generateMipMaps = false;
  13522. internalTexture._generateDepthBuffer = true;
  13523. internalTexture._generateStencilBuffer = generateStencil;
  13524. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13525. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13526. internalTexture._comparisonFunction = comparisonFunction;
  13527. var gl = this._gl;
  13528. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  13529. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  13530. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  13531. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  13532. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13533. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13534. if (comparisonFunction === 0) {
  13535. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  13536. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  13537. }
  13538. else {
  13539. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  13540. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  13541. }
  13542. };
  13543. /**
  13544. * Creates a depth stencil texture.
  13545. * This is only available in WebGL 2 or with the depth texture extension available.
  13546. * @param size The size of face edge in the texture.
  13547. * @param options The options defining the texture.
  13548. * @returns The texture
  13549. */
  13550. Engine.prototype.createDepthStencilTexture = function (size, options) {
  13551. if (options.isCube) {
  13552. var width = size.width || size;
  13553. return this._createDepthStencilCubeTexture(width, options);
  13554. }
  13555. else {
  13556. return this._createDepthStencilTexture(size, options);
  13557. }
  13558. };
  13559. /**
  13560. * Creates a depth stencil texture.
  13561. * This is only available in WebGL 2 or with the depth texture extension available.
  13562. * @param size The size of face edge in the texture.
  13563. * @param options The options defining the texture.
  13564. * @returns The texture
  13565. */
  13566. Engine.prototype._createDepthStencilTexture = function (size, options) {
  13567. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  13568. if (!this._caps.depthTextureExtension) {
  13569. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  13570. return internalTexture;
  13571. }
  13572. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13573. var gl = this._gl;
  13574. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  13575. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13576. if (this.webGLVersion > 1) {
  13577. if (internalOptions.generateStencil) {
  13578. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13579. }
  13580. else {
  13581. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13582. }
  13583. }
  13584. else {
  13585. if (internalOptions.generateStencil) {
  13586. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  13587. }
  13588. else {
  13589. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13590. }
  13591. }
  13592. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13593. return internalTexture;
  13594. };
  13595. /**
  13596. * Creates a depth stencil cube texture.
  13597. * This is only available in WebGL 2.
  13598. * @param size The size of face edge in the cube texture.
  13599. * @param options The options defining the cube texture.
  13600. * @returns The cube texture
  13601. */
  13602. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  13603. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  13604. internalTexture.isCube = true;
  13605. if (this.webGLVersion === 1) {
  13606. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  13607. return internalTexture;
  13608. }
  13609. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  13610. var gl = this._gl;
  13611. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  13612. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  13613. // Create the depth/stencil buffer
  13614. for (var face = 0; face < 6; face++) {
  13615. if (internalOptions.generateStencil) {
  13616. 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);
  13617. }
  13618. else {
  13619. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  13620. }
  13621. }
  13622. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13623. return internalTexture;
  13624. };
  13625. /**
  13626. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  13627. * @param renderTarget The render target to set the frame buffer for
  13628. */
  13629. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  13630. // Create the framebuffer
  13631. var internalTexture = renderTarget.getInternalTexture();
  13632. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  13633. return;
  13634. }
  13635. var gl = this._gl;
  13636. var depthStencilTexture = renderTarget.depthStencilTexture;
  13637. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  13638. if (depthStencilTexture.isCube) {
  13639. if (depthStencilTexture._generateStencilBuffer) {
  13640. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  13641. }
  13642. else {
  13643. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  13644. }
  13645. }
  13646. else {
  13647. if (depthStencilTexture._generateStencilBuffer) {
  13648. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  13649. }
  13650. else {
  13651. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  13652. }
  13653. }
  13654. this.bindUnboundFramebuffer(null);
  13655. };
  13656. Engine.prototype.createRenderTargetTexture = function (size, options) {
  13657. var fullOptions = new RenderTargetCreationOptions();
  13658. if (options !== undefined && typeof options === "object") {
  13659. fullOptions.generateMipMaps = options.generateMipMaps;
  13660. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13661. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  13662. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  13663. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  13664. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  13665. }
  13666. else {
  13667. fullOptions.generateMipMaps = options;
  13668. fullOptions.generateDepthBuffer = true;
  13669. fullOptions.generateStencilBuffer = false;
  13670. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13671. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13672. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  13673. }
  13674. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13675. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13676. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13677. }
  13678. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13679. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13680. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13681. }
  13682. var gl = this._gl;
  13683. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13684. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13685. var width = size.width || size;
  13686. var height = size.height || size;
  13687. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  13688. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13689. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13690. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13691. }
  13692. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13693. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13694. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13695. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13696. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  13697. // Create the framebuffer
  13698. var framebuffer = gl.createFramebuffer();
  13699. this.bindUnboundFramebuffer(framebuffer);
  13700. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13701. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  13702. if (fullOptions.generateMipMaps) {
  13703. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13704. }
  13705. // Unbind
  13706. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13707. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13708. this.bindUnboundFramebuffer(null);
  13709. texture._framebuffer = framebuffer;
  13710. texture.baseWidth = width;
  13711. texture.baseHeight = height;
  13712. texture.width = width;
  13713. texture.height = height;
  13714. texture.isReady = true;
  13715. texture.samples = 1;
  13716. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  13717. texture.samplingMode = fullOptions.samplingMode;
  13718. texture.type = fullOptions.type;
  13719. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  13720. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  13721. // this.resetTextureCache();
  13722. this._internalTexturesCache.push(texture);
  13723. return texture;
  13724. };
  13725. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  13726. var generateMipMaps = false;
  13727. var generateDepthBuffer = true;
  13728. var generateStencilBuffer = false;
  13729. var generateDepthTexture = false;
  13730. var textureCount = 1;
  13731. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  13732. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  13733. var types = [], samplingModes = [];
  13734. if (options !== undefined) {
  13735. generateMipMaps = options.generateMipMaps;
  13736. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  13737. generateStencilBuffer = options.generateStencilBuffer;
  13738. generateDepthTexture = options.generateDepthTexture;
  13739. textureCount = options.textureCount || 1;
  13740. if (options.types) {
  13741. types = options.types;
  13742. }
  13743. if (options.samplingModes) {
  13744. samplingModes = options.samplingModes;
  13745. }
  13746. }
  13747. var gl = this._gl;
  13748. // Create the framebuffer
  13749. var framebuffer = gl.createFramebuffer();
  13750. this.bindUnboundFramebuffer(framebuffer);
  13751. var width = size.width || size;
  13752. var height = size.height || size;
  13753. var textures = [];
  13754. var attachments = [];
  13755. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  13756. for (var i = 0; i < textureCount; i++) {
  13757. var samplingMode = samplingModes[i] || defaultSamplingMode;
  13758. var type = types[i] || defaultType;
  13759. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13760. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13761. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13762. }
  13763. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13764. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13765. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13766. }
  13767. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  13768. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13769. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13770. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  13771. }
  13772. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13773. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13774. textures.push(texture);
  13775. attachments.push(attachment);
  13776. gl.activeTexture(gl["TEXTURE" + i]);
  13777. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  13778. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  13779. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  13780. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13781. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13782. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  13783. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  13784. if (generateMipMaps) {
  13785. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  13786. }
  13787. // Unbind
  13788. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13789. texture._framebuffer = framebuffer;
  13790. texture._depthStencilBuffer = depthStencilBuffer;
  13791. texture.baseWidth = width;
  13792. texture.baseHeight = height;
  13793. texture.width = width;
  13794. texture.height = height;
  13795. texture.isReady = true;
  13796. texture.samples = 1;
  13797. texture.generateMipMaps = generateMipMaps;
  13798. texture.samplingMode = samplingMode;
  13799. texture.type = type;
  13800. texture._generateDepthBuffer = generateDepthBuffer;
  13801. texture._generateStencilBuffer = generateStencilBuffer;
  13802. texture._attachments = attachments;
  13803. this._internalTexturesCache.push(texture);
  13804. }
  13805. if (generateDepthTexture && this._caps.depthTextureExtension) {
  13806. // Depth texture
  13807. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  13808. gl.activeTexture(gl.TEXTURE0);
  13809. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  13810. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  13811. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  13812. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13813. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13814. 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);
  13815. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  13816. depthTexture._framebuffer = framebuffer;
  13817. depthTexture.baseWidth = width;
  13818. depthTexture.baseHeight = height;
  13819. depthTexture.width = width;
  13820. depthTexture.height = height;
  13821. depthTexture.isReady = true;
  13822. depthTexture.samples = 1;
  13823. depthTexture.generateMipMaps = generateMipMaps;
  13824. depthTexture.samplingMode = gl.NEAREST;
  13825. depthTexture._generateDepthBuffer = generateDepthBuffer;
  13826. depthTexture._generateStencilBuffer = generateStencilBuffer;
  13827. textures.push(depthTexture);
  13828. this._internalTexturesCache.push(depthTexture);
  13829. }
  13830. gl.drawBuffers(attachments);
  13831. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13832. this.bindUnboundFramebuffer(null);
  13833. this.resetTextureCache();
  13834. return textures;
  13835. };
  13836. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  13837. if (samples === void 0) { samples = 1; }
  13838. var depthStencilBuffer = null;
  13839. var gl = this._gl;
  13840. // Create the depth/stencil buffer
  13841. if (generateStencilBuffer) {
  13842. depthStencilBuffer = gl.createRenderbuffer();
  13843. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13844. if (samples > 1) {
  13845. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  13846. }
  13847. else {
  13848. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  13849. }
  13850. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13851. }
  13852. else if (generateDepthBuffer) {
  13853. depthStencilBuffer = gl.createRenderbuffer();
  13854. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  13855. if (samples > 1) {
  13856. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  13857. }
  13858. else {
  13859. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  13860. }
  13861. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  13862. }
  13863. return depthStencilBuffer;
  13864. };
  13865. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  13866. if (this.webGLVersion < 2 || !texture) {
  13867. return 1;
  13868. }
  13869. if (texture.samples === samples) {
  13870. return samples;
  13871. }
  13872. var gl = this._gl;
  13873. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13874. // Dispose previous render buffers
  13875. if (texture._depthStencilBuffer) {
  13876. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  13877. texture._depthStencilBuffer = null;
  13878. }
  13879. if (texture._MSAAFramebuffer) {
  13880. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  13881. texture._MSAAFramebuffer = null;
  13882. }
  13883. if (texture._MSAARenderBuffer) {
  13884. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  13885. texture._MSAARenderBuffer = null;
  13886. }
  13887. if (samples > 1) {
  13888. var framebuffer = gl.createFramebuffer();
  13889. if (!framebuffer) {
  13890. throw new Error("Unable to create multi sampled framebuffer");
  13891. }
  13892. texture._MSAAFramebuffer = framebuffer;
  13893. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  13894. var colorRenderbuffer = gl.createRenderbuffer();
  13895. if (!colorRenderbuffer) {
  13896. throw new Error("Unable to create multi sampled framebuffer");
  13897. }
  13898. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13899. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13900. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  13901. texture._MSAARenderBuffer = colorRenderbuffer;
  13902. }
  13903. else {
  13904. this.bindUnboundFramebuffer(texture._framebuffer);
  13905. }
  13906. texture.samples = samples;
  13907. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  13908. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13909. this.bindUnboundFramebuffer(null);
  13910. return samples;
  13911. };
  13912. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  13913. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  13914. return 1;
  13915. }
  13916. if (textures[0].samples === samples) {
  13917. return samples;
  13918. }
  13919. var gl = this._gl;
  13920. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  13921. // Dispose previous render buffers
  13922. if (textures[0]._depthStencilBuffer) {
  13923. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  13924. textures[0]._depthStencilBuffer = null;
  13925. }
  13926. if (textures[0]._MSAAFramebuffer) {
  13927. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  13928. textures[0]._MSAAFramebuffer = null;
  13929. }
  13930. for (var i = 0; i < textures.length; i++) {
  13931. if (textures[i]._MSAARenderBuffer) {
  13932. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  13933. textures[i]._MSAARenderBuffer = null;
  13934. }
  13935. }
  13936. if (samples > 1) {
  13937. var framebuffer = gl.createFramebuffer();
  13938. if (!framebuffer) {
  13939. throw new Error("Unable to create multi sampled framebuffer");
  13940. }
  13941. this.bindUnboundFramebuffer(framebuffer);
  13942. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  13943. var attachments = [];
  13944. for (var i = 0; i < textures.length; i++) {
  13945. var texture = textures[i];
  13946. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13947. var colorRenderbuffer = gl.createRenderbuffer();
  13948. if (!colorRenderbuffer) {
  13949. throw new Error("Unable to create multi sampled framebuffer");
  13950. }
  13951. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  13952. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  13953. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  13954. texture._MSAAFramebuffer = framebuffer;
  13955. texture._MSAARenderBuffer = colorRenderbuffer;
  13956. texture.samples = samples;
  13957. texture._depthStencilBuffer = depthStencilBuffer;
  13958. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  13959. attachments.push(attachment);
  13960. }
  13961. gl.drawBuffers(attachments);
  13962. }
  13963. else {
  13964. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13965. }
  13966. this.bindUnboundFramebuffer(null);
  13967. return samples;
  13968. };
  13969. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  13970. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  13971. };
  13972. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  13973. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  13974. };
  13975. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  13976. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  13977. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  13978. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  13979. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  13980. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13981. }
  13982. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  13983. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  13984. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  13985. }
  13986. var gl = this._gl;
  13987. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  13988. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13989. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  13990. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  13991. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  13992. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  13993. }
  13994. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  13995. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  13996. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  13997. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  13998. for (var face = 0; face < 6; face++) {
  13999. 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);
  14000. }
  14001. // Create the framebuffer
  14002. var framebuffer = gl.createFramebuffer();
  14003. this.bindUnboundFramebuffer(framebuffer);
  14004. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  14005. // MipMaps
  14006. if (fullOptions.generateMipMaps) {
  14007. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14008. }
  14009. // Unbind
  14010. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14011. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  14012. this.bindUnboundFramebuffer(null);
  14013. texture._framebuffer = framebuffer;
  14014. texture.width = size;
  14015. texture.height = size;
  14016. texture.isReady = true;
  14017. texture.isCube = true;
  14018. texture.samples = 1;
  14019. texture.generateMipMaps = fullOptions.generateMipMaps;
  14020. texture.samplingMode = fullOptions.samplingMode;
  14021. texture.type = fullOptions.type;
  14022. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  14023. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  14024. this._internalTexturesCache.push(texture);
  14025. return texture;
  14026. };
  14027. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  14028. var _this = this;
  14029. if (onLoad === void 0) { onLoad = null; }
  14030. if (onError === void 0) { onError = null; }
  14031. if (forcedExtension === void 0) { forcedExtension = null; }
  14032. var callback = function (loadData) {
  14033. if (!loadData) {
  14034. if (onLoad) {
  14035. onLoad(null);
  14036. }
  14037. return;
  14038. }
  14039. var texture = loadData.texture;
  14040. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  14041. texture._lodGenerationScale = scale;
  14042. texture._lodGenerationOffset = offset;
  14043. if (_this._caps.textureLOD) {
  14044. // Do not add extra process if texture lod is supported.
  14045. if (onLoad) {
  14046. onLoad(texture);
  14047. }
  14048. return;
  14049. }
  14050. var mipSlices = 3;
  14051. var gl = _this._gl;
  14052. var width = loadData.width;
  14053. if (!width) {
  14054. return;
  14055. }
  14056. var textures = [];
  14057. for (var i = 0; i < mipSlices; i++) {
  14058. //compute LOD from even spacing in smoothness (matching shader calculation)
  14059. var smoothness = i / (mipSlices - 1);
  14060. var roughness = 1 - smoothness;
  14061. var minLODIndex = offset; // roughness = 0
  14062. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  14063. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  14064. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  14065. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14066. glTextureFromLod.isCube = true;
  14067. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  14068. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14069. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14070. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14071. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14072. if (loadData.isDDS) {
  14073. var info = loadData.info;
  14074. var data = loadData.data;
  14075. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14076. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  14077. }
  14078. else {
  14079. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  14080. }
  14081. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14082. // Wrap in a base texture for easy binding.
  14083. var lodTexture = new BABYLON.BaseTexture(scene);
  14084. lodTexture.isCube = true;
  14085. lodTexture._texture = glTextureFromLod;
  14086. glTextureFromLod.isReady = true;
  14087. textures.push(lodTexture);
  14088. }
  14089. texture._lodTextureHigh = textures[2];
  14090. texture._lodTextureMid = textures[1];
  14091. texture._lodTextureLow = textures[0];
  14092. if (onLoad) {
  14093. onLoad(texture);
  14094. }
  14095. };
  14096. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  14097. };
  14098. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  14099. var _this = this;
  14100. if (onLoad === void 0) { onLoad = null; }
  14101. if (onError === void 0) { onError = null; }
  14102. if (forcedExtension === void 0) { forcedExtension = null; }
  14103. var gl = this._gl;
  14104. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  14105. texture.isCube = true;
  14106. texture.url = rootUrl;
  14107. texture.generateMipMaps = !noMipmap;
  14108. if (!this._doNotHandleContextLost) {
  14109. texture._extension = forcedExtension;
  14110. texture._files = files;
  14111. }
  14112. var isKTX = false;
  14113. var isDDS = false;
  14114. var lastDot = rootUrl.lastIndexOf('.');
  14115. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  14116. if (this._textureFormatInUse) {
  14117. extension = this._textureFormatInUse;
  14118. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  14119. isKTX = true;
  14120. }
  14121. else {
  14122. isDDS = (extension === ".dds");
  14123. }
  14124. var onerror = function (request, exception) {
  14125. if (onError && request) {
  14126. onError(request.status + " " + request.statusText, exception);
  14127. }
  14128. };
  14129. if (isKTX) {
  14130. this._loadFile(rootUrl, function (data) {
  14131. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  14132. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  14133. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14134. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  14135. ktx.uploadLevels(_this._gl, !noMipmap);
  14136. _this.setCubeMapTextureParams(gl, loadMipmap);
  14137. texture.width = ktx.pixelWidth;
  14138. texture.height = ktx.pixelHeight;
  14139. texture.isReady = true;
  14140. }, undefined, undefined, true, onerror);
  14141. }
  14142. else if (isDDS) {
  14143. if (files && files.length === 6) {
  14144. this._cascadeLoadFiles(scene, function (imgs) {
  14145. var info;
  14146. var loadMipmap = false;
  14147. var width = 0;
  14148. for (var index = 0; index < imgs.length; index++) {
  14149. var data = imgs[index];
  14150. info = BABYLON.DDSTools.GetDDSInfo(data);
  14151. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  14152. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14153. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14154. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  14155. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  14156. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14157. }
  14158. texture.width = info.width;
  14159. texture.height = info.height;
  14160. texture.type = info.textureType;
  14161. width = info.width;
  14162. }
  14163. _this.setCubeMapTextureParams(gl, loadMipmap);
  14164. texture.isReady = true;
  14165. if (onLoad) {
  14166. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  14167. }
  14168. }, files, onError);
  14169. }
  14170. else {
  14171. this._loadFile(rootUrl, function (data) {
  14172. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14173. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  14174. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14175. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  14176. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  14177. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  14178. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14179. }
  14180. _this.setCubeMapTextureParams(gl, loadMipmap);
  14181. texture.width = info.width;
  14182. texture.height = info.height;
  14183. texture.isReady = true;
  14184. texture.type = info.textureType;
  14185. if (onLoad) {
  14186. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  14187. }
  14188. }, undefined, undefined, true, onerror);
  14189. }
  14190. }
  14191. else {
  14192. if (!files) {
  14193. throw new Error("Cannot load cubemap because files were not defined");
  14194. }
  14195. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  14196. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  14197. var height = width;
  14198. _this._prepareWorkingCanvas();
  14199. if (!_this._workingCanvas || !_this._workingContext) {
  14200. return;
  14201. }
  14202. _this._workingCanvas.width = width;
  14203. _this._workingCanvas.height = height;
  14204. var faces = [
  14205. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  14206. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  14207. ];
  14208. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14209. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14210. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  14211. for (var index = 0; index < faces.length; index++) {
  14212. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  14213. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14214. }
  14215. if (!noMipmap) {
  14216. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  14217. }
  14218. _this.setCubeMapTextureParams(gl, !noMipmap);
  14219. texture.width = width;
  14220. texture.height = height;
  14221. texture.isReady = true;
  14222. if (format) {
  14223. texture.format = format;
  14224. }
  14225. texture.onLoadedObservable.notifyObservers(texture);
  14226. texture.onLoadedObservable.clear();
  14227. if (onLoad) {
  14228. onLoad();
  14229. }
  14230. }, files, onError);
  14231. }
  14232. this._internalTexturesCache.push(texture);
  14233. return texture;
  14234. };
  14235. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  14236. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14237. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  14238. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14239. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14240. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14241. // this.resetTextureCache();
  14242. };
  14243. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  14244. if (compression === void 0) { compression = null; }
  14245. if (level === void 0) { level = 0; }
  14246. texture._bufferViewArray = data;
  14247. texture.format = format;
  14248. texture.type = type;
  14249. texture.invertY = invertY;
  14250. texture._compression = compression;
  14251. var gl = this._gl;
  14252. var textureType = this._getWebGLTextureType(type);
  14253. var internalFormat = this._getInternalFormat(format);
  14254. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  14255. var needConversion = false;
  14256. if (internalFormat === gl.RGB) {
  14257. internalFormat = gl.RGBA;
  14258. needConversion = true;
  14259. }
  14260. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14261. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14262. if (texture.width % 4 !== 0) {
  14263. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  14264. }
  14265. // Data are known to be in +X +Y +Z -X -Y -Z
  14266. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14267. var faceData = data[faceIndex];
  14268. if (compression) {
  14269. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  14270. }
  14271. else {
  14272. if (needConversion) {
  14273. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  14274. }
  14275. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  14276. }
  14277. }
  14278. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14279. if (isPot && texture.generateMipMaps && level === 0) {
  14280. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14281. }
  14282. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14283. // this.resetTextureCache();
  14284. texture.isReady = true;
  14285. };
  14286. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  14287. if (compression === void 0) { compression = null; }
  14288. var gl = this._gl;
  14289. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  14290. texture.isCube = true;
  14291. texture.generateMipMaps = generateMipMaps;
  14292. texture.format = format;
  14293. texture.type = type;
  14294. if (!this._doNotHandleContextLost) {
  14295. texture._bufferViewArray = data;
  14296. }
  14297. var textureType = this._getWebGLTextureType(type);
  14298. var internalFormat = this._getInternalFormat(format);
  14299. if (internalFormat === gl.RGB) {
  14300. internalFormat = gl.RGBA;
  14301. }
  14302. var width = size;
  14303. var height = width;
  14304. texture.width = width;
  14305. texture.height = height;
  14306. // Double check on POT to generate Mips.
  14307. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  14308. if (!isPot) {
  14309. generateMipMaps = false;
  14310. }
  14311. // Upload data if needed. The texture won't be ready until then.
  14312. if (data) {
  14313. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  14314. }
  14315. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14316. // Filters
  14317. if (data && generateMipMaps) {
  14318. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  14319. }
  14320. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  14321. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14322. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14323. }
  14324. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  14325. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  14326. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  14327. }
  14328. else {
  14329. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  14330. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  14331. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  14332. }
  14333. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14334. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14335. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14336. return texture;
  14337. };
  14338. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  14339. var _this = this;
  14340. if (onLoad === void 0) { onLoad = null; }
  14341. if (onError === void 0) { onError = null; }
  14342. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14343. if (invertY === void 0) { invertY = false; }
  14344. var gl = this._gl;
  14345. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  14346. scene._addPendingData(texture);
  14347. texture.url = url;
  14348. this._internalTexturesCache.push(texture);
  14349. var onerror = function (request, exception) {
  14350. scene._removePendingData(texture);
  14351. if (onError && request) {
  14352. onError(request.status + " " + request.statusText, exception);
  14353. }
  14354. };
  14355. var internalCallback = function (data) {
  14356. var width = texture.width;
  14357. var faceDataArrays = callback(data);
  14358. if (!faceDataArrays) {
  14359. return;
  14360. }
  14361. if (mipmmapGenerator) {
  14362. var textureType = _this._getWebGLTextureType(type);
  14363. var internalFormat = _this._getInternalFormat(format);
  14364. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  14365. var needConversion = false;
  14366. if (internalFormat === gl.RGB) {
  14367. internalFormat = gl.RGBA;
  14368. needConversion = true;
  14369. }
  14370. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  14371. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  14372. var mipData = mipmmapGenerator(faceDataArrays);
  14373. for (var level = 0; level < mipData.length; level++) {
  14374. var mipSize = width >> level;
  14375. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  14376. var mipFaceData = mipData[level][faceIndex];
  14377. if (needConversion) {
  14378. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  14379. }
  14380. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  14381. }
  14382. }
  14383. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  14384. }
  14385. else {
  14386. texture.generateMipMaps = !noMipmap;
  14387. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  14388. }
  14389. texture.isReady = true;
  14390. // this.resetTextureCache();
  14391. scene._removePendingData(texture);
  14392. if (onLoad) {
  14393. onLoad();
  14394. }
  14395. };
  14396. this._loadFile(url, function (data) {
  14397. internalCallback(data);
  14398. }, undefined, scene.database, true, onerror);
  14399. return texture;
  14400. };
  14401. ;
  14402. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  14403. if (compression === void 0) { compression = null; }
  14404. var internalFormat = this._getInternalFormat(format);
  14405. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14406. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14407. if (!this._doNotHandleContextLost) {
  14408. texture._bufferView = data;
  14409. texture.format = format;
  14410. texture.invertY = invertY;
  14411. texture._compression = compression;
  14412. }
  14413. if (texture.width % 4 !== 0) {
  14414. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14415. }
  14416. if (compression && data) {
  14417. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  14418. }
  14419. else {
  14420. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  14421. }
  14422. if (texture.generateMipMaps) {
  14423. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14424. }
  14425. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14426. // this.resetTextureCache();
  14427. texture.isReady = true;
  14428. };
  14429. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  14430. if (compression === void 0) { compression = null; }
  14431. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  14432. texture.baseWidth = width;
  14433. texture.baseHeight = height;
  14434. texture.baseDepth = depth;
  14435. texture.width = width;
  14436. texture.height = height;
  14437. texture.depth = depth;
  14438. texture.format = format;
  14439. texture.generateMipMaps = generateMipMaps;
  14440. texture.samplingMode = samplingMode;
  14441. texture.is3D = true;
  14442. if (!this._doNotHandleContextLost) {
  14443. texture._bufferView = data;
  14444. }
  14445. this.updateRawTexture3D(texture, data, format, invertY, compression);
  14446. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  14447. // Filters
  14448. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14449. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14450. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14451. if (generateMipMaps) {
  14452. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  14453. }
  14454. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14455. this._internalTexturesCache.push(texture);
  14456. return texture;
  14457. };
  14458. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  14459. var gl = this._gl;
  14460. if (!gl) {
  14461. return;
  14462. }
  14463. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  14464. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  14465. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  14466. if (!noMipmap && !isCompressed) {
  14467. gl.generateMipmap(gl.TEXTURE_2D);
  14468. }
  14469. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14470. // this.resetTextureCache();
  14471. if (scene) {
  14472. scene._removePendingData(texture);
  14473. }
  14474. texture.onLoadedObservable.notifyObservers(texture);
  14475. texture.onLoadedObservable.clear();
  14476. };
  14477. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  14478. var _this = this;
  14479. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14480. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  14481. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  14482. var gl = this._gl;
  14483. if (!gl) {
  14484. return;
  14485. }
  14486. if (!texture._webGLTexture) {
  14487. // this.resetTextureCache();
  14488. if (scene) {
  14489. scene._removePendingData(texture);
  14490. }
  14491. return;
  14492. }
  14493. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14494. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14495. texture.baseWidth = width;
  14496. texture.baseHeight = height;
  14497. texture.width = potWidth;
  14498. texture.height = potHeight;
  14499. texture.isReady = true;
  14500. if (processFunction(potWidth, potHeight, function () {
  14501. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14502. })) {
  14503. // Returning as texture needs extra async steps
  14504. return;
  14505. }
  14506. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  14507. };
  14508. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  14509. // Create new RGBA data container.
  14510. var rgbaData;
  14511. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  14512. rgbaData = new Float32Array(width * height * 4);
  14513. }
  14514. else {
  14515. rgbaData = new Uint32Array(width * height * 4);
  14516. }
  14517. // Convert each pixel.
  14518. for (var x = 0; x < width; x++) {
  14519. for (var y = 0; y < height; y++) {
  14520. var index = (y * width + x) * 3;
  14521. var newIndex = (y * width + x) * 4;
  14522. // Map Old Value to new value.
  14523. rgbaData[newIndex + 0] = rgbData[index + 0];
  14524. rgbaData[newIndex + 1] = rgbData[index + 1];
  14525. rgbaData[newIndex + 2] = rgbData[index + 2];
  14526. // Add fully opaque alpha channel.
  14527. rgbaData[newIndex + 3] = 1;
  14528. }
  14529. }
  14530. return rgbaData;
  14531. };
  14532. Engine.prototype._releaseFramebufferObjects = function (texture) {
  14533. var gl = this._gl;
  14534. if (texture._framebuffer) {
  14535. gl.deleteFramebuffer(texture._framebuffer);
  14536. texture._framebuffer = null;
  14537. }
  14538. if (texture._depthStencilBuffer) {
  14539. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  14540. texture._depthStencilBuffer = null;
  14541. }
  14542. if (texture._MSAAFramebuffer) {
  14543. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  14544. texture._MSAAFramebuffer = null;
  14545. }
  14546. if (texture._MSAARenderBuffer) {
  14547. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  14548. texture._MSAARenderBuffer = null;
  14549. }
  14550. };
  14551. Engine.prototype._releaseTexture = function (texture) {
  14552. var gl = this._gl;
  14553. this._releaseFramebufferObjects(texture);
  14554. gl.deleteTexture(texture._webGLTexture);
  14555. // Unbind channels
  14556. this.unbindAllTextures();
  14557. var index = this._internalTexturesCache.indexOf(texture);
  14558. if (index !== -1) {
  14559. this._internalTexturesCache.splice(index, 1);
  14560. }
  14561. // Integrated fixed lod samplers.
  14562. if (texture._lodTextureHigh) {
  14563. texture._lodTextureHigh.dispose();
  14564. }
  14565. if (texture._lodTextureMid) {
  14566. texture._lodTextureMid.dispose();
  14567. }
  14568. if (texture._lodTextureLow) {
  14569. texture._lodTextureLow.dispose();
  14570. }
  14571. // Set output texture of post process to null if the texture has been released/disposed
  14572. this.scenes.forEach(function (scene) {
  14573. scene.postProcesses.forEach(function (postProcess) {
  14574. if (postProcess._outputTexture == texture) {
  14575. postProcess._outputTexture = null;
  14576. }
  14577. });
  14578. scene.cameras.forEach(function (camera) {
  14579. camera._postProcesses.forEach(function (postProcess) {
  14580. if (postProcess) {
  14581. if (postProcess._outputTexture == texture) {
  14582. postProcess._outputTexture = null;
  14583. }
  14584. }
  14585. });
  14586. });
  14587. });
  14588. };
  14589. Engine.prototype.setProgram = function (program) {
  14590. if (this._currentProgram !== program) {
  14591. this._gl.useProgram(program);
  14592. this._currentProgram = program;
  14593. }
  14594. };
  14595. Engine.prototype.bindSamplers = function (effect) {
  14596. this.setProgram(effect.getProgram());
  14597. var samplers = effect.getSamplers();
  14598. for (var index = 0; index < samplers.length; index++) {
  14599. var uniform = effect.getUniform(samplers[index]);
  14600. if (uniform) {
  14601. this._boundUniforms[index] = uniform;
  14602. }
  14603. }
  14604. this._currentEffect = null;
  14605. };
  14606. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  14607. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  14608. return;
  14609. }
  14610. // Remove
  14611. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14612. // Bind last to it
  14613. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  14614. // Bind to dummy
  14615. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  14616. };
  14617. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  14618. if (!internalTexture) {
  14619. return -1;
  14620. }
  14621. internalTexture._initialSlot = channel;
  14622. if (this.disableTextureBindingOptimization) {
  14623. if (channel !== internalTexture._designatedSlot) {
  14624. this._textureCollisions.addCount(1, false);
  14625. }
  14626. }
  14627. else {
  14628. if (channel !== internalTexture._designatedSlot) {
  14629. if (internalTexture._designatedSlot > -1) {
  14630. return internalTexture._designatedSlot;
  14631. }
  14632. else {
  14633. // No slot for this texture, let's pick a new one (if we find a free slot)
  14634. if (this._nextFreeTextureSlots.length) {
  14635. return this._nextFreeTextureSlots[0];
  14636. }
  14637. // We need to recycle the oldest bound texture, sorry.
  14638. this._textureCollisions.addCount(1, false);
  14639. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  14640. }
  14641. }
  14642. }
  14643. return channel;
  14644. };
  14645. Engine.prototype._linkTrackers = function (previous, next) {
  14646. previous.next = next;
  14647. next.previous = previous;
  14648. };
  14649. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  14650. var currentSlot = internalTexture._designatedSlot;
  14651. if (currentSlot === -1) {
  14652. return -1;
  14653. }
  14654. internalTexture._designatedSlot = -1;
  14655. if (this.disableTextureBindingOptimization) {
  14656. return -1;
  14657. }
  14658. // Remove from bound list
  14659. this._linkTrackers(internalTexture.previous, internalTexture.next);
  14660. // Free the slot
  14661. this._boundTexturesCache[currentSlot] = null;
  14662. this._nextFreeTextureSlots.push(currentSlot);
  14663. return currentSlot;
  14664. };
  14665. Engine.prototype._activateCurrentTexture = function () {
  14666. if (this._currentTextureChannel !== this._activeChannel) {
  14667. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  14668. this._currentTextureChannel = this._activeChannel;
  14669. }
  14670. };
  14671. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate) {
  14672. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  14673. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  14674. this._activeChannel = texture._designatedSlot;
  14675. }
  14676. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  14677. var isTextureForRendering = texture && texture._initialSlot > -1;
  14678. if (currentTextureBound !== texture) {
  14679. if (currentTextureBound) {
  14680. this._removeDesignatedSlot(currentTextureBound);
  14681. }
  14682. this._activateCurrentTexture();
  14683. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  14684. this._boundTexturesCache[this._activeChannel] = texture;
  14685. if (texture) {
  14686. if (!this.disableTextureBindingOptimization) {
  14687. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  14688. if (slotIndex > -1) {
  14689. this._nextFreeTextureSlots.splice(slotIndex, 1);
  14690. }
  14691. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  14692. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  14693. }
  14694. texture._designatedSlot = this._activeChannel;
  14695. }
  14696. }
  14697. else if (forTextureDataUpdate) {
  14698. this._activateCurrentTexture();
  14699. }
  14700. if (isTextureForRendering && !forTextureDataUpdate) {
  14701. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  14702. }
  14703. };
  14704. Engine.prototype._bindTexture = function (channel, texture) {
  14705. if (channel < 0) {
  14706. return;
  14707. }
  14708. if (texture) {
  14709. channel = this._getCorrectTextureChannel(channel, texture);
  14710. }
  14711. this._activeChannel = channel;
  14712. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  14713. };
  14714. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  14715. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  14716. };
  14717. /**
  14718. * Binds the output of the passed in post process to the texture channel specified
  14719. * @param channel The channel the texture should be bound to
  14720. * @param postProcess The post process which's output should be bound
  14721. */
  14722. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  14723. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  14724. };
  14725. Engine.prototype.unbindAllTextures = function () {
  14726. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  14727. this._activeChannel = channel;
  14728. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14729. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14730. if (this.webGLVersion > 1) {
  14731. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14732. }
  14733. }
  14734. };
  14735. /**
  14736. * Sets a texture to the according uniform.
  14737. * @param channel The texture channel
  14738. * @param uniform The uniform to set
  14739. * @param texture The texture to apply
  14740. */
  14741. Engine.prototype.setTexture = function (channel, uniform, texture) {
  14742. if (channel < 0) {
  14743. return;
  14744. }
  14745. if (uniform) {
  14746. this._boundUniforms[channel] = uniform;
  14747. }
  14748. this._setTexture(channel, texture);
  14749. };
  14750. /**
  14751. * Sets a depth stencil texture from a render target to the according uniform.
  14752. * @param channel The texture channel
  14753. * @param uniform The uniform to set
  14754. * @param texture The render target texture containing the depth stencil texture to apply
  14755. */
  14756. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  14757. if (channel < 0) {
  14758. return;
  14759. }
  14760. if (uniform) {
  14761. this._boundUniforms[channel] = uniform;
  14762. }
  14763. if (!texture || !texture.depthStencilTexture) {
  14764. this._setTexture(channel, null);
  14765. }
  14766. else {
  14767. this._setTexture(channel, texture, false, true);
  14768. }
  14769. };
  14770. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  14771. var uniform = this._boundUniforms[sourceSlot];
  14772. if (uniform._currentState === destination) {
  14773. return;
  14774. }
  14775. this._gl.uniform1i(uniform, destination);
  14776. uniform._currentState = destination;
  14777. };
  14778. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  14779. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  14780. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  14781. // Not ready?
  14782. if (!texture) {
  14783. if (this._boundTexturesCache[channel] != null) {
  14784. this._activeChannel = channel;
  14785. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14786. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14787. if (this.webGLVersion > 1) {
  14788. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14789. }
  14790. }
  14791. return false;
  14792. }
  14793. // Video
  14794. if (texture.video) {
  14795. this._activeChannel = channel;
  14796. texture.update();
  14797. }
  14798. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  14799. texture.delayLoad();
  14800. return false;
  14801. }
  14802. var internalTexture;
  14803. if (depthStencilTexture) {
  14804. internalTexture = texture.depthStencilTexture;
  14805. }
  14806. else if (texture.isReady()) {
  14807. internalTexture = texture.getInternalTexture();
  14808. }
  14809. else if (texture.isCube) {
  14810. internalTexture = this.emptyCubeTexture;
  14811. }
  14812. else if (texture.is3D) {
  14813. internalTexture = this.emptyTexture3D;
  14814. }
  14815. else {
  14816. internalTexture = this.emptyTexture;
  14817. }
  14818. if (!isPartOfTextureArray) {
  14819. channel = this._getCorrectTextureChannel(channel, internalTexture);
  14820. }
  14821. if (this._boundTexturesCache[channel] === internalTexture) {
  14822. this._moveBoundTextureOnTop(internalTexture);
  14823. if (!isPartOfTextureArray) {
  14824. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  14825. }
  14826. return false;
  14827. }
  14828. this._activeChannel = channel;
  14829. if (internalTexture && internalTexture.is3D) {
  14830. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  14831. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14832. internalTexture._cachedWrapU = texture.wrapU;
  14833. switch (texture.wrapU) {
  14834. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14835. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14836. break;
  14837. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14838. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14839. break;
  14840. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14841. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14842. break;
  14843. }
  14844. }
  14845. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14846. internalTexture._cachedWrapV = texture.wrapV;
  14847. switch (texture.wrapV) {
  14848. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14849. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14850. break;
  14851. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14852. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14853. break;
  14854. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14855. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14856. break;
  14857. }
  14858. }
  14859. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  14860. internalTexture._cachedWrapR = texture.wrapR;
  14861. switch (texture.wrapR) {
  14862. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14863. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.REPEAT);
  14864. break;
  14865. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14866. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.CLAMP_TO_EDGE);
  14867. break;
  14868. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14869. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._gl.MIRRORED_REPEAT);
  14870. break;
  14871. }
  14872. }
  14873. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  14874. }
  14875. else if (internalTexture && internalTexture.isCube) {
  14876. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  14877. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  14878. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  14879. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  14880. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  14881. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  14882. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  14883. }
  14884. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  14885. }
  14886. else {
  14887. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  14888. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  14889. internalTexture._cachedWrapU = texture.wrapU;
  14890. switch (texture.wrapU) {
  14891. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14892. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  14893. break;
  14894. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14895. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  14896. break;
  14897. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14898. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  14899. break;
  14900. }
  14901. }
  14902. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  14903. internalTexture._cachedWrapV = texture.wrapV;
  14904. switch (texture.wrapV) {
  14905. case BABYLON.Texture.WRAP_ADDRESSMODE:
  14906. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  14907. break;
  14908. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  14909. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  14910. break;
  14911. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  14912. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  14913. break;
  14914. }
  14915. }
  14916. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  14917. }
  14918. return true;
  14919. };
  14920. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  14921. if (channel < 0 || !uniform) {
  14922. return;
  14923. }
  14924. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  14925. this._textureUnits = new Int32Array(textures.length);
  14926. }
  14927. for (var i = 0; i < textures.length; i++) {
  14928. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  14929. }
  14930. this._gl.uniform1iv(uniform, this._textureUnits);
  14931. for (var index = 0; index < textures.length; index++) {
  14932. this._setTexture(this._textureUnits[index], textures[index], true);
  14933. }
  14934. };
  14935. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  14936. var internalTexture = texture.getInternalTexture();
  14937. if (!internalTexture) {
  14938. return;
  14939. }
  14940. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  14941. var value = texture.anisotropicFilteringLevel;
  14942. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  14943. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  14944. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  14945. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  14946. }
  14947. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  14948. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  14949. internalTexture._cachedAnisotropicFilteringLevel = value;
  14950. }
  14951. };
  14952. Engine.prototype.readPixels = function (x, y, width, height) {
  14953. var data = new Uint8Array(height * width * 4);
  14954. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  14955. return data;
  14956. };
  14957. /**
  14958. * Add an externaly attached data from its key.
  14959. * This method call will fail and return false, if such key already exists.
  14960. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  14961. * @param key the unique key that identifies the data
  14962. * @param data the data object to associate to the key for this Engine instance
  14963. * @return true if no such key were already present and the data was added successfully, false otherwise
  14964. */
  14965. Engine.prototype.addExternalData = function (key, data) {
  14966. if (!this._externalData) {
  14967. this._externalData = new BABYLON.StringDictionary();
  14968. }
  14969. return this._externalData.add(key, data);
  14970. };
  14971. /**
  14972. * Get an externaly attached data from its key
  14973. * @param key the unique key that identifies the data
  14974. * @return the associated data, if present (can be null), or undefined if not present
  14975. */
  14976. Engine.prototype.getExternalData = function (key) {
  14977. if (!this._externalData) {
  14978. this._externalData = new BABYLON.StringDictionary();
  14979. }
  14980. return this._externalData.get(key);
  14981. };
  14982. /**
  14983. * Get an externaly attached data from its key, create it using a factory if it's not already present
  14984. * @param key the unique key that identifies the data
  14985. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  14986. * @return the associated data, can be null if the factory returned null.
  14987. */
  14988. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  14989. if (!this._externalData) {
  14990. this._externalData = new BABYLON.StringDictionary();
  14991. }
  14992. return this._externalData.getOrAddWithFactory(key, factory);
  14993. };
  14994. /**
  14995. * Remove an externaly attached data from the Engine instance
  14996. * @param key the unique key that identifies the data
  14997. * @return true if the data was successfully removed, false if it doesn't exist
  14998. */
  14999. Engine.prototype.removeExternalData = function (key) {
  15000. if (!this._externalData) {
  15001. this._externalData = new BABYLON.StringDictionary();
  15002. }
  15003. return this._externalData.remove(key);
  15004. };
  15005. Engine.prototype.unbindAllAttributes = function () {
  15006. if (this._mustWipeVertexAttributes) {
  15007. this._mustWipeVertexAttributes = false;
  15008. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  15009. this._gl.disableVertexAttribArray(i);
  15010. this._vertexAttribArraysEnabled[i] = false;
  15011. this._currentBufferPointers[i].active = false;
  15012. }
  15013. return;
  15014. }
  15015. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  15016. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  15017. continue;
  15018. }
  15019. this._gl.disableVertexAttribArray(i);
  15020. this._vertexAttribArraysEnabled[i] = false;
  15021. this._currentBufferPointers[i].active = false;
  15022. }
  15023. };
  15024. Engine.prototype.releaseEffects = function () {
  15025. for (var name in this._compiledEffects) {
  15026. this._deleteProgram(this._compiledEffects[name]._program);
  15027. }
  15028. this._compiledEffects = {};
  15029. };
  15030. // Dispose
  15031. Engine.prototype.dispose = function () {
  15032. this.hideLoadingUI();
  15033. this.stopRenderLoop();
  15034. // Release postProcesses
  15035. while (this.postProcesses.length) {
  15036. this.postProcesses[0].dispose();
  15037. }
  15038. // Empty texture
  15039. if (this._emptyTexture) {
  15040. this._releaseTexture(this._emptyTexture);
  15041. this._emptyTexture = null;
  15042. }
  15043. if (this._emptyCubeTexture) {
  15044. this._releaseTexture(this._emptyCubeTexture);
  15045. this._emptyCubeTexture = null;
  15046. }
  15047. // Rescale PP
  15048. if (this._rescalePostProcess) {
  15049. this._rescalePostProcess.dispose();
  15050. }
  15051. // Release scenes
  15052. while (this.scenes.length) {
  15053. this.scenes[0].dispose();
  15054. }
  15055. // Release audio engine
  15056. if (Engine.audioEngine) {
  15057. Engine.audioEngine.dispose();
  15058. }
  15059. // Release effects
  15060. this.releaseEffects();
  15061. // Unbind
  15062. this.unbindAllAttributes();
  15063. if (this._dummyFramebuffer) {
  15064. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  15065. }
  15066. //WebVR
  15067. this.disableVR();
  15068. // Events
  15069. if (BABYLON.Tools.IsWindowObjectExist()) {
  15070. window.removeEventListener("blur", this._onBlur);
  15071. window.removeEventListener("focus", this._onFocus);
  15072. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  15073. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  15074. if (this._renderingCanvas) {
  15075. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  15076. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  15077. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  15078. if (!this._doNotHandleContextLost) {
  15079. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  15080. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  15081. }
  15082. }
  15083. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  15084. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  15085. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  15086. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  15087. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  15088. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  15089. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  15090. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  15091. if (this._onVrDisplayConnect) {
  15092. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  15093. if (this._onVrDisplayDisconnect) {
  15094. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  15095. }
  15096. if (this._onVrDisplayPresentChange) {
  15097. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  15098. }
  15099. this._onVrDisplayConnect = null;
  15100. this._onVrDisplayDisconnect = null;
  15101. }
  15102. }
  15103. // Remove from Instances
  15104. var index = Engine.Instances.indexOf(this);
  15105. if (index >= 0) {
  15106. Engine.Instances.splice(index, 1);
  15107. }
  15108. this._workingCanvas = null;
  15109. this._workingContext = null;
  15110. this._currentBufferPointers = [];
  15111. this._renderingCanvas = null;
  15112. this._currentProgram = null;
  15113. this._bindedRenderFunction = null;
  15114. this.onResizeObservable.clear();
  15115. this.onCanvasBlurObservable.clear();
  15116. this.onCanvasFocusObservable.clear();
  15117. this.onCanvasPointerOutObservable.clear();
  15118. this.onBeginFrameObservable.clear();
  15119. this.onEndFrameObservable.clear();
  15120. BABYLON.Effect.ResetCache();
  15121. // Abort active requests
  15122. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  15123. var request = _a[_i];
  15124. request.abort();
  15125. }
  15126. };
  15127. // Loading screen
  15128. Engine.prototype.displayLoadingUI = function () {
  15129. if (!BABYLON.Tools.IsWindowObjectExist()) {
  15130. return;
  15131. }
  15132. var loadingScreen = this.loadingScreen;
  15133. if (loadingScreen) {
  15134. loadingScreen.displayLoadingUI();
  15135. }
  15136. };
  15137. Engine.prototype.hideLoadingUI = function () {
  15138. if (!BABYLON.Tools.IsWindowObjectExist()) {
  15139. return;
  15140. }
  15141. var loadingScreen = this.loadingScreen;
  15142. if (loadingScreen) {
  15143. loadingScreen.hideLoadingUI();
  15144. }
  15145. };
  15146. Object.defineProperty(Engine.prototype, "loadingScreen", {
  15147. get: function () {
  15148. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  15149. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  15150. return this._loadingScreen;
  15151. },
  15152. set: function (loadingScreen) {
  15153. this._loadingScreen = loadingScreen;
  15154. },
  15155. enumerable: true,
  15156. configurable: true
  15157. });
  15158. Object.defineProperty(Engine.prototype, "loadingUIText", {
  15159. set: function (text) {
  15160. this.loadingScreen.loadingUIText = text;
  15161. },
  15162. enumerable: true,
  15163. configurable: true
  15164. });
  15165. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  15166. set: function (color) {
  15167. this.loadingScreen.loadingUIBackgroundColor = color;
  15168. },
  15169. enumerable: true,
  15170. configurable: true
  15171. });
  15172. Engine.prototype.attachContextLostEvent = function (callback) {
  15173. if (this._renderingCanvas) {
  15174. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  15175. }
  15176. };
  15177. Engine.prototype.attachContextRestoredEvent = function (callback) {
  15178. if (this._renderingCanvas) {
  15179. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  15180. }
  15181. };
  15182. Engine.prototype.getVertexShaderSource = function (program) {
  15183. var shaders = this._gl.getAttachedShaders(program);
  15184. if (!shaders) {
  15185. return null;
  15186. }
  15187. return this._gl.getShaderSource(shaders[0]);
  15188. };
  15189. Engine.prototype.getFragmentShaderSource = function (program) {
  15190. var shaders = this._gl.getAttachedShaders(program);
  15191. if (!shaders) {
  15192. return null;
  15193. }
  15194. return this._gl.getShaderSource(shaders[1]);
  15195. };
  15196. Engine.prototype.getError = function () {
  15197. return this._gl.getError();
  15198. };
  15199. // FPS
  15200. Engine.prototype.getFps = function () {
  15201. return this._fps;
  15202. };
  15203. Engine.prototype.getDeltaTime = function () {
  15204. return this._deltaTime;
  15205. };
  15206. Engine.prototype._measureFps = function () {
  15207. this._performanceMonitor.sampleFrame();
  15208. this._fps = this._performanceMonitor.averageFPS;
  15209. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  15210. };
  15211. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  15212. if (faceIndex === void 0) { faceIndex = -1; }
  15213. var gl = this._gl;
  15214. if (!this._dummyFramebuffer) {
  15215. var dummy = gl.createFramebuffer();
  15216. if (!dummy) {
  15217. throw new Error("Unable to create dummy framebuffer");
  15218. }
  15219. this._dummyFramebuffer = dummy;
  15220. }
  15221. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  15222. if (faceIndex > -1) {
  15223. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  15224. }
  15225. else {
  15226. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15227. }
  15228. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  15229. var buffer;
  15230. switch (readType) {
  15231. case gl.UNSIGNED_BYTE:
  15232. buffer = new Uint8Array(4 * width * height);
  15233. readType = gl.UNSIGNED_BYTE;
  15234. break;
  15235. default:
  15236. buffer = new Float32Array(4 * width * height);
  15237. readType = gl.FLOAT;
  15238. break;
  15239. }
  15240. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  15241. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  15242. return buffer;
  15243. };
  15244. Engine.prototype._canRenderToFloatFramebuffer = function () {
  15245. if (this._webGLVersion > 1) {
  15246. return this._caps.colorBufferFloat;
  15247. }
  15248. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  15249. };
  15250. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  15251. if (this._webGLVersion > 1) {
  15252. return this._caps.colorBufferFloat;
  15253. }
  15254. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  15255. };
  15256. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  15257. Engine.prototype._canRenderToFramebuffer = function (type) {
  15258. var gl = this._gl;
  15259. //clear existing errors
  15260. while (gl.getError() !== gl.NO_ERROR) { }
  15261. var successful = true;
  15262. var texture = gl.createTexture();
  15263. gl.bindTexture(gl.TEXTURE_2D, texture);
  15264. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15265. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15266. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15267. var fb = gl.createFramebuffer();
  15268. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  15269. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  15270. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  15271. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  15272. successful = successful && (gl.getError() === gl.NO_ERROR);
  15273. //try render by clearing frame buffer's color buffer
  15274. if (successful) {
  15275. gl.clear(gl.COLOR_BUFFER_BIT);
  15276. successful = successful && (gl.getError() === gl.NO_ERROR);
  15277. }
  15278. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  15279. if (successful) {
  15280. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  15281. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15282. var readFormat = gl.RGBA;
  15283. var readType = gl.UNSIGNED_BYTE;
  15284. var buffer = new Uint8Array(4);
  15285. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  15286. successful = successful && (gl.getError() === gl.NO_ERROR);
  15287. }
  15288. //clean up
  15289. gl.deleteTexture(texture);
  15290. gl.deleteFramebuffer(fb);
  15291. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  15292. //clear accumulated errors
  15293. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  15294. return successful;
  15295. };
  15296. Engine.prototype._getWebGLTextureType = function (type) {
  15297. if (type === Engine.TEXTURETYPE_FLOAT) {
  15298. return this._gl.FLOAT;
  15299. }
  15300. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15301. // Add Half Float Constant.
  15302. return this._gl.HALF_FLOAT_OES;
  15303. }
  15304. return this._gl.UNSIGNED_BYTE;
  15305. };
  15306. ;
  15307. Engine.prototype._getInternalFormat = function (format) {
  15308. var internalFormat = this._gl.RGBA;
  15309. switch (format) {
  15310. case Engine.TEXTUREFORMAT_ALPHA:
  15311. internalFormat = this._gl.ALPHA;
  15312. break;
  15313. case Engine.TEXTUREFORMAT_LUMINANCE:
  15314. internalFormat = this._gl.LUMINANCE;
  15315. break;
  15316. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  15317. internalFormat = this._gl.LUMINANCE_ALPHA;
  15318. break;
  15319. case Engine.TEXTUREFORMAT_RGB:
  15320. case Engine.TEXTUREFORMAT_RGB32F:
  15321. internalFormat = this._gl.RGB;
  15322. break;
  15323. case Engine.TEXTUREFORMAT_RGBA:
  15324. case Engine.TEXTUREFORMAT_RGBA32F:
  15325. internalFormat = this._gl.RGBA;
  15326. break;
  15327. case Engine.TEXTUREFORMAT_R32F:
  15328. internalFormat = this._gl.RED;
  15329. break;
  15330. case Engine.TEXTUREFORMAT_RG32F:
  15331. internalFormat = this._gl.RG;
  15332. break;
  15333. }
  15334. return internalFormat;
  15335. };
  15336. /** @ignore */
  15337. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  15338. if (this._webGLVersion === 1) {
  15339. if (format) {
  15340. switch (format) {
  15341. case Engine.TEXTUREFORMAT_LUMINANCE:
  15342. return this._gl.LUMINANCE;
  15343. }
  15344. }
  15345. return this._gl.RGBA;
  15346. }
  15347. if (type === Engine.TEXTURETYPE_FLOAT) {
  15348. if (format) {
  15349. switch (format) {
  15350. case Engine.TEXTUREFORMAT_R32F:
  15351. return this._gl.R32F;
  15352. case Engine.TEXTUREFORMAT_RG32F:
  15353. return this._gl.RG32F;
  15354. case Engine.TEXTUREFORMAT_RGB32F:
  15355. return this._gl.RGB32F;
  15356. }
  15357. }
  15358. return this._gl.RGBA32F;
  15359. }
  15360. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15361. return this._gl.RGBA16F;
  15362. }
  15363. if (format) {
  15364. switch (format) {
  15365. case Engine.TEXTUREFORMAT_LUMINANCE:
  15366. return this._gl.LUMINANCE;
  15367. }
  15368. }
  15369. return this._gl.RGBA;
  15370. };
  15371. ;
  15372. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  15373. if (type === Engine.TEXTURETYPE_FLOAT) {
  15374. return this._gl.RGBA32F;
  15375. }
  15376. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  15377. return this._gl.RGBA16F;
  15378. }
  15379. return this._gl.RGBA8;
  15380. };
  15381. ;
  15382. Engine.prototype.createQuery = function () {
  15383. return this._gl.createQuery();
  15384. };
  15385. Engine.prototype.deleteQuery = function (query) {
  15386. this._gl.deleteQuery(query);
  15387. return this;
  15388. };
  15389. Engine.prototype.isQueryResultAvailable = function (query) {
  15390. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  15391. };
  15392. Engine.prototype.getQueryResult = function (query) {
  15393. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  15394. };
  15395. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  15396. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15397. this._gl.beginQuery(glAlgorithm, query);
  15398. return this;
  15399. };
  15400. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  15401. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  15402. this._gl.endQuery(glAlgorithm);
  15403. return this;
  15404. };
  15405. /* Time queries */
  15406. Engine.prototype._createTimeQuery = function () {
  15407. var timerQuery = this._caps.timerQuery;
  15408. if (timerQuery.createQueryEXT) {
  15409. return timerQuery.createQueryEXT();
  15410. }
  15411. return this.createQuery();
  15412. };
  15413. Engine.prototype._deleteTimeQuery = function (query) {
  15414. var timerQuery = this._caps.timerQuery;
  15415. if (timerQuery.deleteQueryEXT) {
  15416. timerQuery.deleteQueryEXT(query);
  15417. return;
  15418. }
  15419. this.deleteQuery(query);
  15420. };
  15421. Engine.prototype._getTimeQueryResult = function (query) {
  15422. var timerQuery = this._caps.timerQuery;
  15423. if (timerQuery.getQueryObjectEXT) {
  15424. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  15425. }
  15426. return this.getQueryResult(query);
  15427. };
  15428. Engine.prototype._getTimeQueryAvailability = function (query) {
  15429. var timerQuery = this._caps.timerQuery;
  15430. if (timerQuery.getQueryObjectEXT) {
  15431. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  15432. }
  15433. return this.isQueryResultAvailable(query);
  15434. };
  15435. Engine.prototype.startTimeQuery = function () {
  15436. var timerQuery = this._caps.timerQuery;
  15437. if (!timerQuery) {
  15438. return null;
  15439. }
  15440. var token = new BABYLON._TimeToken();
  15441. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15442. if (this._caps.canUseTimestampForTimerQuery) {
  15443. token._startTimeQuery = this._createTimeQuery();
  15444. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  15445. }
  15446. else {
  15447. if (this._currentNonTimestampToken) {
  15448. return this._currentNonTimestampToken;
  15449. }
  15450. token._timeElapsedQuery = this._createTimeQuery();
  15451. if (timerQuery.beginQueryEXT) {
  15452. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15453. }
  15454. else {
  15455. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  15456. }
  15457. this._currentNonTimestampToken = token;
  15458. }
  15459. return token;
  15460. };
  15461. Engine.prototype.endTimeQuery = function (token) {
  15462. var timerQuery = this._caps.timerQuery;
  15463. if (!timerQuery || !token) {
  15464. return -1;
  15465. }
  15466. if (this._caps.canUseTimestampForTimerQuery) {
  15467. if (!token._startTimeQuery) {
  15468. return -1;
  15469. }
  15470. if (!token._endTimeQuery) {
  15471. token._endTimeQuery = this._createTimeQuery();
  15472. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  15473. }
  15474. }
  15475. else if (!token._timeElapsedQueryEnded) {
  15476. if (!token._timeElapsedQuery) {
  15477. return -1;
  15478. }
  15479. if (timerQuery.endQueryEXT) {
  15480. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  15481. }
  15482. else {
  15483. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  15484. }
  15485. token._timeElapsedQueryEnded = true;
  15486. }
  15487. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  15488. var available = false;
  15489. if (token._endTimeQuery) {
  15490. available = this._getTimeQueryAvailability(token._endTimeQuery);
  15491. }
  15492. else if (token._timeElapsedQuery) {
  15493. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  15494. }
  15495. if (available && !disjoint) {
  15496. var result = 0;
  15497. if (this._caps.canUseTimestampForTimerQuery) {
  15498. if (!token._startTimeQuery || !token._endTimeQuery) {
  15499. return -1;
  15500. }
  15501. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  15502. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  15503. result = timeEnd - timeStart;
  15504. this._deleteTimeQuery(token._startTimeQuery);
  15505. this._deleteTimeQuery(token._endTimeQuery);
  15506. token._startTimeQuery = null;
  15507. token._endTimeQuery = null;
  15508. }
  15509. else {
  15510. if (!token._timeElapsedQuery) {
  15511. return -1;
  15512. }
  15513. result = this._getTimeQueryResult(token._timeElapsedQuery);
  15514. this._deleteTimeQuery(token._timeElapsedQuery);
  15515. token._timeElapsedQuery = null;
  15516. token._timeElapsedQueryEnded = false;
  15517. this._currentNonTimestampToken = null;
  15518. }
  15519. return result;
  15520. }
  15521. return -1;
  15522. };
  15523. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  15524. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  15525. };
  15526. // Transform feedback
  15527. Engine.prototype.createTransformFeedback = function () {
  15528. return this._gl.createTransformFeedback();
  15529. };
  15530. Engine.prototype.deleteTransformFeedback = function (value) {
  15531. this._gl.deleteTransformFeedback(value);
  15532. };
  15533. Engine.prototype.bindTransformFeedback = function (value) {
  15534. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  15535. };
  15536. Engine.prototype.beginTransformFeedback = function (usePoints) {
  15537. if (usePoints === void 0) { usePoints = true; }
  15538. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  15539. };
  15540. Engine.prototype.endTransformFeedback = function () {
  15541. this._gl.endTransformFeedback();
  15542. };
  15543. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  15544. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  15545. };
  15546. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  15547. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  15548. };
  15549. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  15550. var _this = this;
  15551. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  15552. this._activeRequests.push(request);
  15553. request.onCompleteObservable.add(function (request) {
  15554. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  15555. });
  15556. return request;
  15557. };
  15558. /** @ignore */
  15559. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  15560. var _this = this;
  15561. return new Promise(function (resolve, reject) {
  15562. _this._loadFile(url, function (data) {
  15563. resolve(data);
  15564. }, undefined, database, useArrayBuffer, function (request, exception) {
  15565. reject(exception);
  15566. });
  15567. });
  15568. };
  15569. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  15570. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15571. var onload = function (data) {
  15572. loadedFiles[index] = data;
  15573. loadedFiles._internalCount++;
  15574. if (loadedFiles._internalCount === 6) {
  15575. onfinish(loadedFiles);
  15576. }
  15577. };
  15578. var onerror = function (request, exception) {
  15579. if (onErrorCallBack && request) {
  15580. onErrorCallBack(request.status + " " + request.statusText, exception);
  15581. }
  15582. };
  15583. this._loadFile(url, onload, undefined, undefined, true, onerror);
  15584. };
  15585. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  15586. if (onError === void 0) { onError = null; }
  15587. var loadedFiles = [];
  15588. loadedFiles._internalCount = 0;
  15589. for (var index = 0; index < 6; index++) {
  15590. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  15591. }
  15592. };
  15593. // Statics
  15594. Engine.isSupported = function () {
  15595. try {
  15596. var tempcanvas = document.createElement("canvas");
  15597. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  15598. return gl != null && !!window.WebGLRenderingContext;
  15599. }
  15600. catch (e) {
  15601. return false;
  15602. }
  15603. };
  15604. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  15605. Engine.ExceptionList = [
  15606. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  15607. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15608. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  15609. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15610. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  15611. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  15612. ];
  15613. Engine.Instances = new Array();
  15614. // Const statics
  15615. Engine._ALPHA_DISABLE = 0;
  15616. Engine._ALPHA_ADD = 1;
  15617. Engine._ALPHA_COMBINE = 2;
  15618. Engine._ALPHA_SUBTRACT = 3;
  15619. Engine._ALPHA_MULTIPLY = 4;
  15620. Engine._ALPHA_MAXIMIZED = 5;
  15621. Engine._ALPHA_ONEONE = 6;
  15622. Engine._ALPHA_PREMULTIPLIED = 7;
  15623. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  15624. Engine._ALPHA_INTERPOLATE = 9;
  15625. Engine._ALPHA_SCREENMODE = 10;
  15626. Engine._DELAYLOADSTATE_NONE = 0;
  15627. Engine._DELAYLOADSTATE_LOADED = 1;
  15628. Engine._DELAYLOADSTATE_LOADING = 2;
  15629. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  15630. Engine._TEXTUREFORMAT_ALPHA = 0;
  15631. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  15632. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  15633. Engine._TEXTUREFORMAT_RGB = 4;
  15634. Engine._TEXTUREFORMAT_RGBA = 5;
  15635. Engine._TEXTUREFORMAT_R32F = 6;
  15636. Engine._TEXTUREFORMAT_RG32F = 7;
  15637. Engine._TEXTUREFORMAT_RGB32F = 8;
  15638. Engine._TEXTUREFORMAT_RGBA32F = 9;
  15639. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  15640. Engine._TEXTURETYPE_FLOAT = 1;
  15641. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  15642. // Depht or Stencil test Constants.
  15643. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  15644. 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.
  15645. 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.
  15646. 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.
  15647. 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.
  15648. 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.
  15649. 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.
  15650. 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.
  15651. // Stencil Actions Constants.
  15652. Engine._KEEP = 0x1E00;
  15653. Engine._REPLACE = 0x1E01;
  15654. Engine._INCR = 0x1E02;
  15655. Engine._DECR = 0x1E03;
  15656. Engine._INVERT = 0x150A;
  15657. Engine._INCR_WRAP = 0x8507;
  15658. Engine._DECR_WRAP = 0x8508;
  15659. // Texture rescaling mode
  15660. Engine._SCALEMODE_FLOOR = 1;
  15661. Engine._SCALEMODE_NEAREST = 2;
  15662. Engine._SCALEMODE_CEILING = 3;
  15663. // Updatable statics so stick with vars here
  15664. Engine.CollisionsEpsilon = 0.001;
  15665. Engine.CodeRepository = "src/";
  15666. Engine.ShadersRepository = "src/Shaders/";
  15667. return Engine;
  15668. }());
  15669. BABYLON.Engine = Engine;
  15670. })(BABYLON || (BABYLON = {}));
  15671. //# sourceMappingURL=babylon.engine.js.map
  15672. "use strict";
  15673. var BABYLON;
  15674. (function (BABYLON) {
  15675. /**
  15676. * Node is the basic class for all scene objects (Mesh, Light Camera).
  15677. */
  15678. var Node = /** @class */ (function () {
  15679. /**
  15680. * Creates a new Node
  15681. * @param {string} name - the name and id to be given to this node
  15682. * @param {BABYLON.Scene} the scene this node will be added to
  15683. */
  15684. function Node(name, scene) {
  15685. if (scene === void 0) { scene = null; }
  15686. /**
  15687. * Gets or sets a string used to store user defined state for the node
  15688. */
  15689. this.state = "";
  15690. /**
  15691. * Gets or sets an object used to store user defined information for the node
  15692. */
  15693. this.metadata = null;
  15694. /**
  15695. * Gets or sets a boolean used to define if the node must be serialized
  15696. */
  15697. this.doNotSerialize = false;
  15698. /** @ignore */
  15699. this._isDisposed = false;
  15700. /**
  15701. * Gets a list of {BABYLON.Animation} associated with the node
  15702. */
  15703. this.animations = new Array();
  15704. this._ranges = {};
  15705. this._isEnabled = true;
  15706. this._isReady = true;
  15707. /** @ignore */
  15708. this._currentRenderId = -1;
  15709. this._parentRenderId = -1;
  15710. this._animationPropertiesOverride = null;
  15711. /**
  15712. * An event triggered when the mesh is disposed
  15713. * @type {BABYLON.Observable}
  15714. */
  15715. this.onDisposeObservable = new BABYLON.Observable();
  15716. // Behaviors
  15717. this._behaviors = new Array();
  15718. this.name = name;
  15719. this.id = name;
  15720. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  15721. this.uniqueId = this._scene.getUniqueId();
  15722. this._initCache();
  15723. }
  15724. /**
  15725. * Gets a boolean indicating if the node has been disposed
  15726. * @returns true if the node was disposed
  15727. */
  15728. Node.prototype.isDisposed = function () {
  15729. return this._isDisposed;
  15730. };
  15731. Object.defineProperty(Node.prototype, "parent", {
  15732. get: function () {
  15733. return this._parentNode;
  15734. },
  15735. /**
  15736. * Gets or sets the parent of the node
  15737. */
  15738. set: function (parent) {
  15739. if (this._parentNode === parent) {
  15740. return;
  15741. }
  15742. // Remove self from list of children of parent
  15743. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  15744. var index = this._parentNode._children.indexOf(this);
  15745. if (index !== -1) {
  15746. this._parentNode._children.splice(index, 1);
  15747. }
  15748. }
  15749. // Store new parent
  15750. this._parentNode = parent;
  15751. // Add as child to new parent
  15752. if (this._parentNode) {
  15753. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  15754. this._parentNode._children = new Array();
  15755. }
  15756. this._parentNode._children.push(this);
  15757. }
  15758. },
  15759. enumerable: true,
  15760. configurable: true
  15761. });
  15762. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  15763. /**
  15764. * Gets or sets the animation properties override
  15765. */
  15766. get: function () {
  15767. return this._animationPropertiesOverride;
  15768. },
  15769. set: function (value) {
  15770. this._animationPropertiesOverride = value;
  15771. },
  15772. enumerable: true,
  15773. configurable: true
  15774. });
  15775. /**
  15776. * Gets a string idenfifying the name of the class
  15777. * @returns "Node" string
  15778. */
  15779. Node.prototype.getClassName = function () {
  15780. return "Node";
  15781. };
  15782. Object.defineProperty(Node.prototype, "onDispose", {
  15783. /**
  15784. * Sets a callback that will be raised when the node will be disposed
  15785. */
  15786. set: function (callback) {
  15787. if (this._onDisposeObserver) {
  15788. this.onDisposeObservable.remove(this._onDisposeObserver);
  15789. }
  15790. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  15791. },
  15792. enumerable: true,
  15793. configurable: true
  15794. });
  15795. /**
  15796. * Gets the scene of the node
  15797. * @returns a {BABYLON.Scene}
  15798. */
  15799. Node.prototype.getScene = function () {
  15800. return this._scene;
  15801. };
  15802. /**
  15803. * Gets the engine of the node
  15804. * @returns a {BABYLON.Engine}
  15805. */
  15806. Node.prototype.getEngine = function () {
  15807. return this._scene.getEngine();
  15808. };
  15809. /**
  15810. * Attach a behavior to the node
  15811. * @see http://doc.babylonjs.com/features/behaviour
  15812. * @param behavior defines the behavior to attach
  15813. * @returns the current Node
  15814. */
  15815. Node.prototype.addBehavior = function (behavior) {
  15816. var _this = this;
  15817. var index = this._behaviors.indexOf(behavior);
  15818. if (index !== -1) {
  15819. return this;
  15820. }
  15821. behavior.init();
  15822. if (this._scene.isLoading) {
  15823. // We defer the attach when the scene will be loaded
  15824. var observer = this._scene.onDataLoadedObservable.add(function () {
  15825. behavior.attach(_this);
  15826. setTimeout(function () {
  15827. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  15828. _this._scene.onDataLoadedObservable.remove(observer);
  15829. }, 0);
  15830. });
  15831. }
  15832. else {
  15833. behavior.attach(this);
  15834. }
  15835. this._behaviors.push(behavior);
  15836. return this;
  15837. };
  15838. /**
  15839. * Remove an attached behavior
  15840. * @see http://doc.babylonjs.com/features/behaviour
  15841. * @param behavior defines the behavior to attach
  15842. * @returns the current Node
  15843. */
  15844. Node.prototype.removeBehavior = function (behavior) {
  15845. var index = this._behaviors.indexOf(behavior);
  15846. if (index === -1) {
  15847. return this;
  15848. }
  15849. this._behaviors[index].detach();
  15850. this._behaviors.splice(index, 1);
  15851. return this;
  15852. };
  15853. Object.defineProperty(Node.prototype, "behaviors", {
  15854. /**
  15855. * Gets the list of attached behaviors
  15856. * @see http://doc.babylonjs.com/features/behaviour
  15857. */
  15858. get: function () {
  15859. return this._behaviors;
  15860. },
  15861. enumerable: true,
  15862. configurable: true
  15863. });
  15864. /**
  15865. * Gets an attached behavior by name
  15866. * @param name defines the name of the behavior to look for
  15867. * @see http://doc.babylonjs.com/features/behaviour
  15868. * @returns null if behavior was not found else the requested behavior
  15869. */
  15870. Node.prototype.getBehaviorByName = function (name) {
  15871. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  15872. var behavior = _a[_i];
  15873. if (behavior.name === name) {
  15874. return behavior;
  15875. }
  15876. }
  15877. return null;
  15878. };
  15879. /**
  15880. * Returns the world matrix of the node
  15881. * @returns a matrix containing the node's world matrix
  15882. */
  15883. Node.prototype.getWorldMatrix = function () {
  15884. return BABYLON.Matrix.Identity();
  15885. };
  15886. // override it in derived class if you add new variables to the cache
  15887. // and call the parent class method
  15888. /** @ignore */
  15889. Node.prototype._initCache = function () {
  15890. this._cache = {};
  15891. this._cache.parent = undefined;
  15892. };
  15893. /** @ignore */
  15894. Node.prototype.updateCache = function (force) {
  15895. if (!force && this.isSynchronized())
  15896. return;
  15897. this._cache.parent = this.parent;
  15898. this._updateCache();
  15899. };
  15900. // override it in derived class if you add new variables to the cache
  15901. // and call the parent class method if !ignoreParentClass
  15902. /** @ignore */
  15903. Node.prototype._updateCache = function (ignoreParentClass) {
  15904. };
  15905. // override it in derived class if you add new variables to the cache
  15906. /** @ignore */
  15907. Node.prototype._isSynchronized = function () {
  15908. return true;
  15909. };
  15910. /** @ignore */
  15911. Node.prototype._markSyncedWithParent = function () {
  15912. if (this.parent) {
  15913. this._parentRenderId = this.parent._currentRenderId;
  15914. }
  15915. };
  15916. /** @ignore */
  15917. Node.prototype.isSynchronizedWithParent = function () {
  15918. if (!this.parent) {
  15919. return true;
  15920. }
  15921. if (this._parentRenderId !== this.parent._currentRenderId) {
  15922. return false;
  15923. }
  15924. return this.parent.isSynchronized();
  15925. };
  15926. /** @ignore */
  15927. Node.prototype.isSynchronized = function (updateCache) {
  15928. var check = this.hasNewParent();
  15929. check = check || !this.isSynchronizedWithParent();
  15930. check = check || !this._isSynchronized();
  15931. if (updateCache)
  15932. this.updateCache(true);
  15933. return !check;
  15934. };
  15935. /** @ignore */
  15936. Node.prototype.hasNewParent = function (update) {
  15937. if (this._cache.parent === this.parent)
  15938. return false;
  15939. if (update)
  15940. this._cache.parent = this.parent;
  15941. return true;
  15942. };
  15943. /**
  15944. * Is this node ready to be used/rendered
  15945. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  15946. * @return true if the node is ready
  15947. */
  15948. Node.prototype.isReady = function (completeCheck) {
  15949. if (completeCheck === void 0) { completeCheck = false; }
  15950. return this._isReady;
  15951. };
  15952. /**
  15953. * Is this node enabled?
  15954. * 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
  15955. * @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
  15956. * @return whether this node (and its parent) is enabled
  15957. * @see setEnabled
  15958. */
  15959. Node.prototype.isEnabled = function (checkAncestors) {
  15960. if (checkAncestors === void 0) { checkAncestors = true; }
  15961. if (checkAncestors === false) {
  15962. return this._isEnabled;
  15963. }
  15964. if (this._isEnabled === false) {
  15965. return false;
  15966. }
  15967. if (this.parent !== undefined && this.parent !== null) {
  15968. return this.parent.isEnabled(checkAncestors);
  15969. }
  15970. return true;
  15971. };
  15972. /**
  15973. * Set the enabled state of this node
  15974. * @param value defines the new enabled state
  15975. * @see isEnabled
  15976. */
  15977. Node.prototype.setEnabled = function (value) {
  15978. this._isEnabled = value;
  15979. };
  15980. /**
  15981. * Is this node a descendant of the given node?
  15982. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  15983. * @param ancestor defines the parent node to inspect
  15984. * @see parent
  15985. * @returns a boolean indicating if this node is a descendant of the given node
  15986. */
  15987. Node.prototype.isDescendantOf = function (ancestor) {
  15988. if (this.parent) {
  15989. if (this.parent === ancestor) {
  15990. return true;
  15991. }
  15992. return this.parent.isDescendantOf(ancestor);
  15993. }
  15994. return false;
  15995. };
  15996. /** @ignore */
  15997. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  15998. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  15999. if (!this._children) {
  16000. return;
  16001. }
  16002. for (var index = 0; index < this._children.length; index++) {
  16003. var item = this._children[index];
  16004. if (!predicate || predicate(item)) {
  16005. results.push(item);
  16006. }
  16007. if (!directDescendantsOnly) {
  16008. item._getDescendants(results, false, predicate);
  16009. }
  16010. }
  16011. };
  16012. /**
  16013. * Will return all nodes that have this node as ascendant
  16014. * @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
  16015. * @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
  16016. * @return all children nodes of all types
  16017. */
  16018. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  16019. var results = new Array();
  16020. this._getDescendants(results, directDescendantsOnly, predicate);
  16021. return results;
  16022. };
  16023. /**
  16024. * Get all child-meshes of this node
  16025. * @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
  16026. * @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
  16027. * @returns an array of {BABYLON.AbstractMesh}
  16028. */
  16029. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  16030. var results = [];
  16031. this._getDescendants(results, directDescendantsOnly, function (node) {
  16032. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  16033. });
  16034. return results;
  16035. };
  16036. /**
  16037. * Get all child-transformNodes of this node
  16038. * @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
  16039. * @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
  16040. * @returns an array of {BABYLON.TransformNode}
  16041. */
  16042. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  16043. var results = [];
  16044. this._getDescendants(results, directDescendantsOnly, function (node) {
  16045. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  16046. });
  16047. return results;
  16048. };
  16049. /**
  16050. * Get all direct children of this node
  16051. * @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
  16052. * @returns an array of {BABYLON.Node}
  16053. */
  16054. Node.prototype.getChildren = function (predicate) {
  16055. return this.getDescendants(true, predicate);
  16056. };
  16057. /** @ignore */
  16058. Node.prototype._setReady = function (state) {
  16059. if (state === this._isReady) {
  16060. return;
  16061. }
  16062. if (!state) {
  16063. this._isReady = false;
  16064. return;
  16065. }
  16066. if (this.onReady) {
  16067. this.onReady(this);
  16068. }
  16069. this._isReady = true;
  16070. };
  16071. /**
  16072. * Get an animation by name
  16073. * @param name defines the name of the animation to look for
  16074. * @returns null if not found else the requested animation
  16075. */
  16076. Node.prototype.getAnimationByName = function (name) {
  16077. for (var i = 0; i < this.animations.length; i++) {
  16078. var animation = this.animations[i];
  16079. if (animation.name === name) {
  16080. return animation;
  16081. }
  16082. }
  16083. return null;
  16084. };
  16085. /**
  16086. * Creates an animation range for this node
  16087. * @param name defines the name of the range
  16088. * @param from defines the starting key
  16089. * @param to defines the end key
  16090. */
  16091. Node.prototype.createAnimationRange = function (name, from, to) {
  16092. // check name not already in use
  16093. if (!this._ranges[name]) {
  16094. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  16095. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  16096. if (this.animations[i]) {
  16097. this.animations[i].createRange(name, from, to);
  16098. }
  16099. }
  16100. }
  16101. };
  16102. /**
  16103. * Delete a specific animation range
  16104. * @param name defines the name of the range to delete
  16105. * @param deleteFrames defines if animation frames from the range must be deleted as well
  16106. */
  16107. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  16108. if (deleteFrames === void 0) { deleteFrames = true; }
  16109. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  16110. if (this.animations[i]) {
  16111. this.animations[i].deleteRange(name, deleteFrames);
  16112. }
  16113. }
  16114. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  16115. };
  16116. /**
  16117. * Get an animation range by name
  16118. * @param name defines the name of the animation range to look for
  16119. * @returns null if not found else the requested animation range
  16120. */
  16121. Node.prototype.getAnimationRange = function (name) {
  16122. return this._ranges[name];
  16123. };
  16124. /**
  16125. * Will start the animation sequence
  16126. * @param name defines the range frames for animation sequence
  16127. * @param loop defines if the animation should loop (false by default)
  16128. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  16129. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  16130. * @returns the object created for this animation. If range does not exist, it will return null
  16131. */
  16132. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  16133. var range = this.getAnimationRange(name);
  16134. if (!range) {
  16135. return null;
  16136. }
  16137. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  16138. };
  16139. /**
  16140. * Serialize animation ranges into a JSON compatible object
  16141. * @returns serialization object
  16142. */
  16143. Node.prototype.serializeAnimationRanges = function () {
  16144. var serializationRanges = [];
  16145. for (var name in this._ranges) {
  16146. var localRange = this._ranges[name];
  16147. if (!localRange) {
  16148. continue;
  16149. }
  16150. var range = {};
  16151. range.name = name;
  16152. range.from = localRange.from;
  16153. range.to = localRange.to;
  16154. serializationRanges.push(range);
  16155. }
  16156. return serializationRanges;
  16157. };
  16158. /**
  16159. * Computes the world matrix of the node
  16160. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  16161. * @returns the world matrix
  16162. */
  16163. Node.prototype.computeWorldMatrix = function (force) {
  16164. return BABYLON.Matrix.Identity();
  16165. };
  16166. /**
  16167. * Releases resources associated with this node.
  16168. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  16169. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  16170. */
  16171. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  16172. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  16173. if (!doNotRecurse) {
  16174. var nodes = this.getDescendants(true);
  16175. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  16176. var node = nodes_1[_i];
  16177. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  16178. }
  16179. }
  16180. else {
  16181. var transformNodes = this.getChildTransformNodes(true);
  16182. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  16183. var transformNode = transformNodes_1[_a];
  16184. transformNode.parent = null;
  16185. transformNode.computeWorldMatrix(true);
  16186. }
  16187. }
  16188. this.parent = null;
  16189. // Callback
  16190. this.onDisposeObservable.notifyObservers(this);
  16191. this.onDisposeObservable.clear();
  16192. // Behaviors
  16193. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  16194. var behavior = _c[_b];
  16195. behavior.detach();
  16196. }
  16197. this._behaviors = [];
  16198. this._isDisposed = true;
  16199. };
  16200. /**
  16201. * Parse animation range data from a serialization object and store them into a given node
  16202. * @param node defines where to store the animation ranges
  16203. * @param parsedNode defines the serialization object to read data from
  16204. * @param scene defines the hosting scene
  16205. */
  16206. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  16207. if (parsedNode.ranges) {
  16208. for (var index = 0; index < parsedNode.ranges.length; index++) {
  16209. var data = parsedNode.ranges[index];
  16210. node.createAnimationRange(data.name, data.from, data.to);
  16211. }
  16212. }
  16213. };
  16214. __decorate([
  16215. BABYLON.serialize()
  16216. ], Node.prototype, "name", void 0);
  16217. __decorate([
  16218. BABYLON.serialize()
  16219. ], Node.prototype, "id", void 0);
  16220. __decorate([
  16221. BABYLON.serialize()
  16222. ], Node.prototype, "uniqueId", void 0);
  16223. __decorate([
  16224. BABYLON.serialize()
  16225. ], Node.prototype, "state", void 0);
  16226. __decorate([
  16227. BABYLON.serialize()
  16228. ], Node.prototype, "metadata", void 0);
  16229. return Node;
  16230. }());
  16231. BABYLON.Node = Node;
  16232. })(BABYLON || (BABYLON = {}));
  16233. //# sourceMappingURL=babylon.node.js.map
  16234. "use strict";
  16235. var BABYLON;
  16236. (function (BABYLON) {
  16237. var BoundingSphere = /** @class */ (function () {
  16238. function BoundingSphere(minimum, maximum) {
  16239. this.minimum = minimum;
  16240. this.maximum = maximum;
  16241. this._tempRadiusVector = BABYLON.Vector3.Zero();
  16242. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  16243. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  16244. this.radius = distance * 0.5;
  16245. this.centerWorld = BABYLON.Vector3.Zero();
  16246. this._update(BABYLON.Matrix.Identity());
  16247. }
  16248. // Methods
  16249. BoundingSphere.prototype._update = function (world) {
  16250. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  16251. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  16252. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  16253. };
  16254. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  16255. for (var i = 0; i < 6; i++) {
  16256. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  16257. return false;
  16258. }
  16259. return true;
  16260. };
  16261. BoundingSphere.prototype.intersectsPoint = function (point) {
  16262. var x = this.centerWorld.x - point.x;
  16263. var y = this.centerWorld.y - point.y;
  16264. var z = this.centerWorld.z - point.z;
  16265. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  16266. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  16267. return false;
  16268. return true;
  16269. };
  16270. // Statics
  16271. BoundingSphere.Intersects = function (sphere0, sphere1) {
  16272. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  16273. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  16274. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  16275. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  16276. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  16277. return false;
  16278. return true;
  16279. };
  16280. return BoundingSphere;
  16281. }());
  16282. BABYLON.BoundingSphere = BoundingSphere;
  16283. })(BABYLON || (BABYLON = {}));
  16284. //# sourceMappingURL=babylon.boundingSphere.js.map
  16285. "use strict";
  16286. var BABYLON;
  16287. (function (BABYLON) {
  16288. var BoundingBox = /** @class */ (function () {
  16289. function BoundingBox(minimum, maximum) {
  16290. this.minimum = minimum;
  16291. this.maximum = maximum;
  16292. this.vectors = new Array();
  16293. this.vectorsWorld = new Array();
  16294. // Bounding vectors
  16295. this.vectors.push(this.minimum.clone());
  16296. this.vectors.push(this.maximum.clone());
  16297. this.vectors.push(this.minimum.clone());
  16298. this.vectors[2].x = this.maximum.x;
  16299. this.vectors.push(this.minimum.clone());
  16300. this.vectors[3].y = this.maximum.y;
  16301. this.vectors.push(this.minimum.clone());
  16302. this.vectors[4].z = this.maximum.z;
  16303. this.vectors.push(this.maximum.clone());
  16304. this.vectors[5].z = this.minimum.z;
  16305. this.vectors.push(this.maximum.clone());
  16306. this.vectors[6].x = this.minimum.x;
  16307. this.vectors.push(this.maximum.clone());
  16308. this.vectors[7].y = this.minimum.y;
  16309. // OBB
  16310. this.center = this.maximum.add(this.minimum).scale(0.5);
  16311. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  16312. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  16313. // World
  16314. for (var index = 0; index < this.vectors.length; index++) {
  16315. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  16316. }
  16317. this.minimumWorld = BABYLON.Vector3.Zero();
  16318. this.maximumWorld = BABYLON.Vector3.Zero();
  16319. this.centerWorld = BABYLON.Vector3.Zero();
  16320. this.extendSizeWorld = BABYLON.Vector3.Zero();
  16321. this._update(BABYLON.Matrix.Identity());
  16322. }
  16323. // Methods
  16324. BoundingBox.prototype.getWorldMatrix = function () {
  16325. return this._worldMatrix;
  16326. };
  16327. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  16328. this._worldMatrix.copyFrom(matrix);
  16329. return this;
  16330. };
  16331. BoundingBox.prototype._update = function (world) {
  16332. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  16333. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  16334. for (var index = 0; index < this.vectors.length; index++) {
  16335. var v = this.vectorsWorld[index];
  16336. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  16337. if (v.x < this.minimumWorld.x)
  16338. this.minimumWorld.x = v.x;
  16339. if (v.y < this.minimumWorld.y)
  16340. this.minimumWorld.y = v.y;
  16341. if (v.z < this.minimumWorld.z)
  16342. this.minimumWorld.z = v.z;
  16343. if (v.x > this.maximumWorld.x)
  16344. this.maximumWorld.x = v.x;
  16345. if (v.y > this.maximumWorld.y)
  16346. this.maximumWorld.y = v.y;
  16347. if (v.z > this.maximumWorld.z)
  16348. this.maximumWorld.z = v.z;
  16349. }
  16350. // Extend
  16351. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  16352. this.extendSizeWorld.scaleInPlace(0.5);
  16353. // OBB
  16354. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  16355. this.centerWorld.scaleInPlace(0.5);
  16356. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  16357. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  16358. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  16359. this._worldMatrix = world;
  16360. };
  16361. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  16362. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  16363. };
  16364. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16365. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  16366. };
  16367. BoundingBox.prototype.intersectsPoint = function (point) {
  16368. var delta = -BABYLON.Epsilon;
  16369. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  16370. return false;
  16371. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  16372. return false;
  16373. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  16374. return false;
  16375. return true;
  16376. };
  16377. BoundingBox.prototype.intersectsSphere = function (sphere) {
  16378. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  16379. };
  16380. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  16381. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  16382. return false;
  16383. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  16384. return false;
  16385. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  16386. return false;
  16387. return true;
  16388. };
  16389. // Statics
  16390. BoundingBox.Intersects = function (box0, box1) {
  16391. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  16392. return false;
  16393. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  16394. return false;
  16395. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  16396. return false;
  16397. return true;
  16398. };
  16399. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  16400. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  16401. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  16402. return (num <= (sphereRadius * sphereRadius));
  16403. };
  16404. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  16405. for (var p = 0; p < 6; p++) {
  16406. for (var i = 0; i < 8; i++) {
  16407. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16408. return false;
  16409. }
  16410. }
  16411. }
  16412. return true;
  16413. };
  16414. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  16415. for (var p = 0; p < 6; p++) {
  16416. var inCount = 8;
  16417. for (var i = 0; i < 8; i++) {
  16418. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  16419. --inCount;
  16420. }
  16421. else {
  16422. break;
  16423. }
  16424. }
  16425. if (inCount === 0)
  16426. return false;
  16427. }
  16428. return true;
  16429. };
  16430. return BoundingBox;
  16431. }());
  16432. BABYLON.BoundingBox = BoundingBox;
  16433. })(BABYLON || (BABYLON = {}));
  16434. //# sourceMappingURL=babylon.boundingBox.js.map
  16435. "use strict";
  16436. var BABYLON;
  16437. (function (BABYLON) {
  16438. var computeBoxExtents = function (axis, box) {
  16439. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  16440. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  16441. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  16442. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  16443. var r = r0 + r1 + r2;
  16444. return {
  16445. min: p - r,
  16446. max: p + r
  16447. };
  16448. };
  16449. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  16450. var axisOverlap = function (axis, box0, box1) {
  16451. var result0 = computeBoxExtents(axis, box0);
  16452. var result1 = computeBoxExtents(axis, box1);
  16453. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  16454. };
  16455. var BoundingInfo = /** @class */ (function () {
  16456. function BoundingInfo(minimum, maximum) {
  16457. this.minimum = minimum;
  16458. this.maximum = maximum;
  16459. this._isLocked = false;
  16460. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  16461. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  16462. }
  16463. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  16464. get: function () {
  16465. return this._isLocked;
  16466. },
  16467. set: function (value) {
  16468. this._isLocked = value;
  16469. },
  16470. enumerable: true,
  16471. configurable: true
  16472. });
  16473. // Methods
  16474. BoundingInfo.prototype.update = function (world) {
  16475. if (this._isLocked) {
  16476. return;
  16477. }
  16478. this.boundingBox._update(world);
  16479. this.boundingSphere._update(world);
  16480. };
  16481. /**
  16482. * Recreate the bounding info to be centered around a specific point given a specific extend.
  16483. * @param center New center of the bounding info
  16484. * @param extend New extend of the bounding info
  16485. */
  16486. BoundingInfo.prototype.centerOn = function (center, extend) {
  16487. this.minimum = center.subtract(extend);
  16488. this.maximum = center.add(extend);
  16489. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  16490. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  16491. return this;
  16492. };
  16493. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  16494. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  16495. return false;
  16496. return this.boundingBox.isInFrustum(frustumPlanes);
  16497. };
  16498. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  16499. /**
  16500. * Gets the world distance between the min and max points of the bounding box
  16501. */
  16502. get: function () {
  16503. var boundingBox = this.boundingBox;
  16504. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  16505. return size.length();
  16506. },
  16507. enumerable: true,
  16508. configurable: true
  16509. });
  16510. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  16511. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  16512. };
  16513. BoundingInfo.prototype._checkCollision = function (collider) {
  16514. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  16515. };
  16516. BoundingInfo.prototype.intersectsPoint = function (point) {
  16517. if (!this.boundingSphere.centerWorld) {
  16518. return false;
  16519. }
  16520. if (!this.boundingSphere.intersectsPoint(point)) {
  16521. return false;
  16522. }
  16523. if (!this.boundingBox.intersectsPoint(point)) {
  16524. return false;
  16525. }
  16526. return true;
  16527. };
  16528. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  16529. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  16530. return false;
  16531. }
  16532. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  16533. return false;
  16534. }
  16535. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  16536. return false;
  16537. }
  16538. if (!precise) {
  16539. return true;
  16540. }
  16541. var box0 = this.boundingBox;
  16542. var box1 = boundingInfo.boundingBox;
  16543. if (!axisOverlap(box0.directions[0], box0, box1))
  16544. return false;
  16545. if (!axisOverlap(box0.directions[1], box0, box1))
  16546. return false;
  16547. if (!axisOverlap(box0.directions[2], box0, box1))
  16548. return false;
  16549. if (!axisOverlap(box1.directions[0], box0, box1))
  16550. return false;
  16551. if (!axisOverlap(box1.directions[1], box0, box1))
  16552. return false;
  16553. if (!axisOverlap(box1.directions[2], box0, box1))
  16554. return false;
  16555. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  16556. return false;
  16557. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  16558. return false;
  16559. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  16560. return false;
  16561. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  16562. return false;
  16563. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  16564. return false;
  16565. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  16566. return false;
  16567. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  16568. return false;
  16569. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  16570. return false;
  16571. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  16572. return false;
  16573. return true;
  16574. };
  16575. return BoundingInfo;
  16576. }());
  16577. BABYLON.BoundingInfo = BoundingInfo;
  16578. })(BABYLON || (BABYLON = {}));
  16579. //# sourceMappingURL=babylon.boundingInfo.js.map
  16580. "use strict";
  16581. var BABYLON;
  16582. (function (BABYLON) {
  16583. var TransformNode = /** @class */ (function (_super) {
  16584. __extends(TransformNode, _super);
  16585. function TransformNode(name, scene, isPure) {
  16586. if (scene === void 0) { scene = null; }
  16587. if (isPure === void 0) { isPure = true; }
  16588. var _this = _super.call(this, name, scene) || this;
  16589. // Properties
  16590. _this._rotation = BABYLON.Vector3.Zero();
  16591. _this._scaling = BABYLON.Vector3.One();
  16592. _this._isDirty = false;
  16593. _this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_NONE;
  16594. _this.scalingDeterminant = 1;
  16595. _this.infiniteDistance = false;
  16596. _this.position = BABYLON.Vector3.Zero();
  16597. _this._localWorld = BABYLON.Matrix.Zero();
  16598. _this._worldMatrix = BABYLON.Matrix.Zero();
  16599. _this._worldMatrixDeterminant = 0;
  16600. _this._absolutePosition = BABYLON.Vector3.Zero();
  16601. _this._pivotMatrix = BABYLON.Matrix.Identity();
  16602. _this._postMultiplyPivotMatrix = false;
  16603. _this._isWorldMatrixFrozen = false;
  16604. /**
  16605. * An event triggered after the world matrix is updated
  16606. * @type {BABYLON.Observable}
  16607. */
  16608. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  16609. _this._nonUniformScaling = false;
  16610. if (isPure) {
  16611. _this.getScene().addTransformNode(_this);
  16612. }
  16613. return _this;
  16614. }
  16615. /**
  16616. * Gets a string idenfifying the name of the class
  16617. * @returns "TransformNode" string
  16618. */
  16619. TransformNode.prototype.getClassName = function () {
  16620. return "TransformNode";
  16621. };
  16622. Object.defineProperty(TransformNode.prototype, "rotation", {
  16623. /**
  16624. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  16625. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  16626. * Default : (0.0, 0.0, 0.0)
  16627. */
  16628. get: function () {
  16629. return this._rotation;
  16630. },
  16631. set: function (newRotation) {
  16632. this._rotation = newRotation;
  16633. },
  16634. enumerable: true,
  16635. configurable: true
  16636. });
  16637. Object.defineProperty(TransformNode.prototype, "scaling", {
  16638. /**
  16639. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16640. * Default : (1.0, 1.0, 1.0)
  16641. */
  16642. get: function () {
  16643. return this._scaling;
  16644. },
  16645. /**
  16646. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  16647. * Default : (1.0, 1.0, 1.0)
  16648. */
  16649. set: function (newScaling) {
  16650. this._scaling = newScaling;
  16651. },
  16652. enumerable: true,
  16653. configurable: true
  16654. });
  16655. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  16656. /**
  16657. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  16658. * It's null by default.
  16659. * 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)
  16660. */
  16661. get: function () {
  16662. return this._rotationQuaternion;
  16663. },
  16664. set: function (quaternion) {
  16665. this._rotationQuaternion = quaternion;
  16666. //reset the rotation vector.
  16667. if (quaternion && this.rotation.length()) {
  16668. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  16669. }
  16670. },
  16671. enumerable: true,
  16672. configurable: true
  16673. });
  16674. /**
  16675. * Returns the latest update of the World matrix
  16676. * Returns a Matrix.
  16677. */
  16678. TransformNode.prototype.getWorldMatrix = function () {
  16679. if (this._currentRenderId !== this.getScene().getRenderId()) {
  16680. this.computeWorldMatrix();
  16681. }
  16682. return this._worldMatrix;
  16683. };
  16684. /**
  16685. * Returns the latest update of the World matrix determinant.
  16686. */
  16687. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  16688. return this._worldMatrixDeterminant;
  16689. };
  16690. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  16691. /**
  16692. * Returns directly the latest state of the mesh World matrix.
  16693. * A Matrix is returned.
  16694. */
  16695. get: function () {
  16696. return this._worldMatrix;
  16697. },
  16698. enumerable: true,
  16699. configurable: true
  16700. });
  16701. /**
  16702. * Copies the paramater passed Matrix into the mesh Pose matrix.
  16703. * Returns the AbstractMesh.
  16704. */
  16705. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  16706. this._poseMatrix.copyFrom(matrix);
  16707. return this;
  16708. };
  16709. /**
  16710. * Returns the mesh Pose matrix.
  16711. * Returned object : Matrix
  16712. */
  16713. TransformNode.prototype.getPoseMatrix = function () {
  16714. return this._poseMatrix;
  16715. };
  16716. TransformNode.prototype._isSynchronized = function () {
  16717. if (this._isDirty) {
  16718. return false;
  16719. }
  16720. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE)
  16721. return false;
  16722. if (this._cache.pivotMatrixUpdated) {
  16723. return false;
  16724. }
  16725. if (this.infiniteDistance) {
  16726. return false;
  16727. }
  16728. if (!this._cache.position.equals(this.position))
  16729. return false;
  16730. if (this.rotationQuaternion) {
  16731. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  16732. return false;
  16733. }
  16734. if (!this._cache.rotation.equals(this.rotation))
  16735. return false;
  16736. if (!this._cache.scaling.equals(this.scaling))
  16737. return false;
  16738. return true;
  16739. };
  16740. TransformNode.prototype._initCache = function () {
  16741. _super.prototype._initCache.call(this);
  16742. this._cache.localMatrixUpdated = false;
  16743. this._cache.position = BABYLON.Vector3.Zero();
  16744. this._cache.scaling = BABYLON.Vector3.Zero();
  16745. this._cache.rotation = BABYLON.Vector3.Zero();
  16746. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  16747. this._cache.billboardMode = -1;
  16748. };
  16749. TransformNode.prototype.markAsDirty = function (property) {
  16750. if (property === "rotation") {
  16751. this.rotationQuaternion = null;
  16752. }
  16753. this._currentRenderId = Number.MAX_VALUE;
  16754. this._isDirty = true;
  16755. return this;
  16756. };
  16757. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  16758. /**
  16759. * Returns the current mesh absolute position.
  16760. * Retuns a Vector3.
  16761. */
  16762. get: function () {
  16763. return this._absolutePosition;
  16764. },
  16765. enumerable: true,
  16766. configurable: true
  16767. });
  16768. /**
  16769. * Sets a new matrix to apply before all other transformation
  16770. * @param matrix defines the transform matrix
  16771. * @returns the current TransformNode
  16772. */
  16773. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  16774. return this.setPivotMatrix(matrix, false);
  16775. };
  16776. /**
  16777. * Sets a new pivot matrix to the current node
  16778. * @param matrix defines the new pivot matrix to use
  16779. * @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
  16780. * @returns the current TransformNode
  16781. */
  16782. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  16783. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  16784. this._pivotMatrix = matrix.clone();
  16785. this._cache.pivotMatrixUpdated = true;
  16786. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  16787. if (this._postMultiplyPivotMatrix) {
  16788. if (!this._pivotMatrixInverse) {
  16789. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  16790. }
  16791. else {
  16792. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  16793. }
  16794. }
  16795. return this;
  16796. };
  16797. /**
  16798. * Returns the mesh pivot matrix.
  16799. * Default : Identity.
  16800. * A Matrix is returned.
  16801. */
  16802. TransformNode.prototype.getPivotMatrix = function () {
  16803. return this._pivotMatrix;
  16804. };
  16805. /**
  16806. * Prevents the World matrix to be computed any longer.
  16807. * Returns the AbstractMesh.
  16808. */
  16809. TransformNode.prototype.freezeWorldMatrix = function () {
  16810. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  16811. this.computeWorldMatrix(true);
  16812. this._isWorldMatrixFrozen = true;
  16813. return this;
  16814. };
  16815. /**
  16816. * Allows back the World matrix computation.
  16817. * Returns the AbstractMesh.
  16818. */
  16819. TransformNode.prototype.unfreezeWorldMatrix = function () {
  16820. this._isWorldMatrixFrozen = false;
  16821. this.computeWorldMatrix(true);
  16822. return this;
  16823. };
  16824. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  16825. /**
  16826. * True if the World matrix has been frozen.
  16827. * Returns a boolean.
  16828. */
  16829. get: function () {
  16830. return this._isWorldMatrixFrozen;
  16831. },
  16832. enumerable: true,
  16833. configurable: true
  16834. });
  16835. /**
  16836. * Retuns the mesh absolute position in the World.
  16837. * Returns a Vector3.
  16838. */
  16839. TransformNode.prototype.getAbsolutePosition = function () {
  16840. this.computeWorldMatrix();
  16841. return this._absolutePosition;
  16842. };
  16843. /**
  16844. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  16845. * Returns the AbstractMesh.
  16846. */
  16847. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  16848. if (!absolutePosition) {
  16849. return this;
  16850. }
  16851. var absolutePositionX;
  16852. var absolutePositionY;
  16853. var absolutePositionZ;
  16854. if (absolutePosition.x === undefined) {
  16855. if (arguments.length < 3) {
  16856. return this;
  16857. }
  16858. absolutePositionX = arguments[0];
  16859. absolutePositionY = arguments[1];
  16860. absolutePositionZ = arguments[2];
  16861. }
  16862. else {
  16863. absolutePositionX = absolutePosition.x;
  16864. absolutePositionY = absolutePosition.y;
  16865. absolutePositionZ = absolutePosition.z;
  16866. }
  16867. if (this.parent) {
  16868. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  16869. invertParentWorldMatrix.invert();
  16870. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  16871. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  16872. }
  16873. else {
  16874. this.position.x = absolutePositionX;
  16875. this.position.y = absolutePositionY;
  16876. this.position.z = absolutePositionZ;
  16877. }
  16878. return this;
  16879. };
  16880. /**
  16881. * Sets the mesh position in its local space.
  16882. * Returns the AbstractMesh.
  16883. */
  16884. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  16885. this.computeWorldMatrix();
  16886. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  16887. return this;
  16888. };
  16889. /**
  16890. * Returns the mesh position in the local space from the current World matrix values.
  16891. * Returns a new Vector3.
  16892. */
  16893. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  16894. this.computeWorldMatrix();
  16895. var invLocalWorldMatrix = this._localWorld.clone();
  16896. invLocalWorldMatrix.invert();
  16897. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  16898. };
  16899. /**
  16900. * Translates the mesh along the passed Vector3 in its local space.
  16901. * Returns the AbstractMesh.
  16902. */
  16903. TransformNode.prototype.locallyTranslate = function (vector3) {
  16904. this.computeWorldMatrix(true);
  16905. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  16906. return this;
  16907. };
  16908. /**
  16909. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  16910. * @param targetPoint the position (must be in same space as current mesh) to look at
  16911. * @param yawCor optional yaw (y-axis) correction in radians
  16912. * @param pitchCor optional pitch (x-axis) correction in radians
  16913. * @param rollCor optional roll (z-axis) correction in radians
  16914. * @param space the choosen space of the target
  16915. * @returns the TransformNode.
  16916. */
  16917. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  16918. if (yawCor === void 0) { yawCor = 0; }
  16919. if (pitchCor === void 0) { pitchCor = 0; }
  16920. if (rollCor === void 0) { rollCor = 0; }
  16921. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16922. var dv = BABYLON.AbstractMesh._lookAtVectorCache;
  16923. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  16924. targetPoint.subtractToRef(pos, dv);
  16925. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  16926. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  16927. var pitch = Math.atan2(dv.y, len);
  16928. if (this.rotationQuaternion) {
  16929. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  16930. }
  16931. else {
  16932. this.rotation.x = pitch + pitchCor;
  16933. this.rotation.y = yaw + yawCor;
  16934. this.rotation.z = rollCor;
  16935. }
  16936. return this;
  16937. };
  16938. /**
  16939. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  16940. * This Vector3 is expressed in the World space.
  16941. */
  16942. TransformNode.prototype.getDirection = function (localAxis) {
  16943. var result = BABYLON.Vector3.Zero();
  16944. this.getDirectionToRef(localAxis, result);
  16945. return result;
  16946. };
  16947. /**
  16948. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  16949. * localAxis is expressed in the mesh local space.
  16950. * result is computed in the Wordl space from the mesh World matrix.
  16951. * Returns the AbstractMesh.
  16952. */
  16953. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  16954. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  16955. return this;
  16956. };
  16957. /**
  16958. * Sets a new pivot point to the current node
  16959. * @param point defines the new pivot point to use
  16960. * @param space defines if the point is in world or local space (local by default)
  16961. * @returns the current TransformNode
  16962. */
  16963. TransformNode.prototype.setPivotPoint = function (point, space) {
  16964. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  16965. if (this.getScene().getRenderId() == 0) {
  16966. this.computeWorldMatrix(true);
  16967. }
  16968. var wm = this.getWorldMatrix();
  16969. if (space == BABYLON.Space.WORLD) {
  16970. var tmat = BABYLON.Tmp.Matrix[0];
  16971. wm.invertToRef(tmat);
  16972. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  16973. }
  16974. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  16975. };
  16976. /**
  16977. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  16978. */
  16979. TransformNode.prototype.getPivotPoint = function () {
  16980. var point = BABYLON.Vector3.Zero();
  16981. this.getPivotPointToRef(point);
  16982. return point;
  16983. };
  16984. /**
  16985. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  16986. * Returns the AbstractMesh.
  16987. */
  16988. TransformNode.prototype.getPivotPointToRef = function (result) {
  16989. result.x = -this._pivotMatrix.m[12];
  16990. result.y = -this._pivotMatrix.m[13];
  16991. result.z = -this._pivotMatrix.m[14];
  16992. return this;
  16993. };
  16994. /**
  16995. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  16996. */
  16997. TransformNode.prototype.getAbsolutePivotPoint = function () {
  16998. var point = BABYLON.Vector3.Zero();
  16999. this.getAbsolutePivotPointToRef(point);
  17000. return point;
  17001. };
  17002. /**
  17003. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  17004. * Returns the AbstractMesh.
  17005. */
  17006. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  17007. result.x = this._pivotMatrix.m[12];
  17008. result.y = this._pivotMatrix.m[13];
  17009. result.z = this._pivotMatrix.m[14];
  17010. this.getPivotPointToRef(result);
  17011. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  17012. return this;
  17013. };
  17014. /**
  17015. * Defines the passed node as the parent of the current node.
  17016. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  17017. * Returns the TransformNode.
  17018. */
  17019. TransformNode.prototype.setParent = function (node) {
  17020. if (node === null) {
  17021. var rotation = BABYLON.Tmp.Quaternion[0];
  17022. var position = BABYLON.Tmp.Vector3[0];
  17023. var scale = BABYLON.Tmp.Vector3[1];
  17024. if (this.parent && this.parent.computeWorldMatrix) {
  17025. this.parent.computeWorldMatrix(true);
  17026. }
  17027. this.computeWorldMatrix(true);
  17028. this.getWorldMatrix().decompose(scale, rotation, position);
  17029. if (this.rotationQuaternion) {
  17030. this.rotationQuaternion.copyFrom(rotation);
  17031. }
  17032. else {
  17033. rotation.toEulerAnglesToRef(this.rotation);
  17034. }
  17035. this.scaling.x = scale.x;
  17036. this.scaling.y = scale.y;
  17037. this.scaling.z = scale.z;
  17038. this.position.x = position.x;
  17039. this.position.y = position.y;
  17040. this.position.z = position.z;
  17041. }
  17042. else {
  17043. var rotation = BABYLON.Tmp.Quaternion[0];
  17044. var position = BABYLON.Tmp.Vector3[0];
  17045. var scale = BABYLON.Tmp.Vector3[1];
  17046. var diffMatrix = BABYLON.Tmp.Matrix[0];
  17047. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  17048. this.computeWorldMatrix(true);
  17049. node.computeWorldMatrix(true);
  17050. node.getWorldMatrix().invertToRef(invParentMatrix);
  17051. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  17052. diffMatrix.decompose(scale, rotation, position);
  17053. if (this.rotationQuaternion) {
  17054. this.rotationQuaternion.copyFrom(rotation);
  17055. }
  17056. else {
  17057. rotation.toEulerAnglesToRef(this.rotation);
  17058. }
  17059. this.position.x = position.x;
  17060. this.position.y = position.y;
  17061. this.position.z = position.z;
  17062. this.scaling.x = scale.x;
  17063. this.scaling.y = scale.y;
  17064. this.scaling.z = scale.z;
  17065. }
  17066. this.parent = node;
  17067. return this;
  17068. };
  17069. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  17070. get: function () {
  17071. return this._nonUniformScaling;
  17072. },
  17073. enumerable: true,
  17074. configurable: true
  17075. });
  17076. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  17077. if (this._nonUniformScaling === value) {
  17078. return false;
  17079. }
  17080. this._nonUniformScaling = true;
  17081. return true;
  17082. };
  17083. /**
  17084. * Attach the current TransformNode to another TransformNode associated with a bone
  17085. * @param bone Bone affecting the TransformNode
  17086. * @param affectedTransformNode TransformNode associated with the bone
  17087. */
  17088. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  17089. this._transformToBoneReferal = affectedTransformNode;
  17090. this.parent = bone;
  17091. if (bone.getWorldMatrix().determinant() < 0) {
  17092. this.scalingDeterminant *= -1;
  17093. }
  17094. return this;
  17095. };
  17096. TransformNode.prototype.detachFromBone = function () {
  17097. if (!this.parent) {
  17098. return this;
  17099. }
  17100. if (this.parent.getWorldMatrix().determinant() < 0) {
  17101. this.scalingDeterminant *= -1;
  17102. }
  17103. this._transformToBoneReferal = null;
  17104. this.parent = null;
  17105. return this;
  17106. };
  17107. /**
  17108. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  17109. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  17110. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  17111. * The passed axis is also normalized.
  17112. * Returns the AbstractMesh.
  17113. */
  17114. TransformNode.prototype.rotate = function (axis, amount, space) {
  17115. axis.normalize();
  17116. if (!this.rotationQuaternion) {
  17117. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17118. this.rotation = BABYLON.Vector3.Zero();
  17119. }
  17120. var rotationQuaternion;
  17121. if (!space || space === BABYLON.Space.LOCAL) {
  17122. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  17123. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  17124. }
  17125. else {
  17126. if (this.parent) {
  17127. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  17128. invertParentWorldMatrix.invert();
  17129. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  17130. }
  17131. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, BABYLON.AbstractMesh._rotationAxisCache);
  17132. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  17133. }
  17134. return this;
  17135. };
  17136. /**
  17137. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  17138. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  17139. * The passed axis is also normalized.
  17140. * Returns the AbstractMesh.
  17141. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  17142. */
  17143. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  17144. axis.normalize();
  17145. if (!this.rotationQuaternion) {
  17146. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  17147. this.rotation.copyFromFloats(0, 0, 0);
  17148. }
  17149. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  17150. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  17151. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  17152. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  17153. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  17154. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  17155. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  17156. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  17157. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  17158. return this;
  17159. };
  17160. /**
  17161. * Translates the mesh along the axis vector for the passed distance in the given space.
  17162. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  17163. * Returns the AbstractMesh.
  17164. */
  17165. TransformNode.prototype.translate = function (axis, distance, space) {
  17166. var displacementVector = axis.scale(distance);
  17167. if (!space || space === BABYLON.Space.LOCAL) {
  17168. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  17169. this.setPositionWithLocalVector(tempV3);
  17170. }
  17171. else {
  17172. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  17173. }
  17174. return this;
  17175. };
  17176. /**
  17177. * Adds a rotation step to the mesh current rotation.
  17178. * x, y, z are Euler angles expressed in radians.
  17179. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  17180. * This means this rotation is made in the mesh local space only.
  17181. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  17182. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  17183. * ```javascript
  17184. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  17185. * ```
  17186. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  17187. * 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.
  17188. * Returns the AbstractMesh.
  17189. */
  17190. TransformNode.prototype.addRotation = function (x, y, z) {
  17191. var rotationQuaternion;
  17192. if (this.rotationQuaternion) {
  17193. rotationQuaternion = this.rotationQuaternion;
  17194. }
  17195. else {
  17196. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  17197. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  17198. }
  17199. var accumulation = BABYLON.Tmp.Quaternion[0];
  17200. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  17201. rotationQuaternion.multiplyInPlace(accumulation);
  17202. if (!this.rotationQuaternion) {
  17203. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  17204. }
  17205. return this;
  17206. };
  17207. /**
  17208. * Computes the mesh World matrix and returns it.
  17209. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  17210. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  17211. * If the parameter `force`is set to `true`, the actual computation is done.
  17212. * Returns the mesh World Matrix.
  17213. */
  17214. TransformNode.prototype.computeWorldMatrix = function (force) {
  17215. if (this._isWorldMatrixFrozen) {
  17216. return this._worldMatrix;
  17217. }
  17218. if (!force && this.isSynchronized(true)) {
  17219. return this._worldMatrix;
  17220. }
  17221. this._cache.position.copyFrom(this.position);
  17222. this._cache.scaling.copyFrom(this.scaling);
  17223. this._cache.pivotMatrixUpdated = false;
  17224. this._cache.billboardMode = this.billboardMode;
  17225. this._currentRenderId = this.getScene().getRenderId();
  17226. this._isDirty = false;
  17227. // Scaling
  17228. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  17229. // Rotation
  17230. //rotate, if quaternion is set and rotation was used
  17231. if (this.rotationQuaternion) {
  17232. var len = this.rotation.length();
  17233. if (len) {
  17234. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  17235. this.rotation.copyFromFloats(0, 0, 0);
  17236. }
  17237. }
  17238. if (this.rotationQuaternion) {
  17239. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  17240. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  17241. }
  17242. else {
  17243. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  17244. this._cache.rotation.copyFrom(this.rotation);
  17245. }
  17246. // Translation
  17247. var camera = this.getScene().activeCamera;
  17248. if (this.infiniteDistance && !this.parent && camera) {
  17249. var cameraWorldMatrix = camera.getWorldMatrix();
  17250. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  17251. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  17252. }
  17253. else {
  17254. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  17255. }
  17256. // Composing transformations
  17257. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  17258. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  17259. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  17260. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE && camera) {
  17261. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_ALL) !== BABYLON.AbstractMesh.BILLBOARDMODE_ALL) {
  17262. // Need to decompose each rotation here
  17263. var currentPosition = BABYLON.Tmp.Vector3[3];
  17264. if (this.parent && this.parent.getWorldMatrix) {
  17265. if (this._transformToBoneReferal) {
  17266. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17267. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  17268. }
  17269. else {
  17270. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  17271. }
  17272. }
  17273. else {
  17274. currentPosition.copyFrom(this.position);
  17275. }
  17276. currentPosition.subtractInPlace(camera.globalPosition);
  17277. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  17278. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_X) === BABYLON.AbstractMesh.BILLBOARDMODE_X) {
  17279. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  17280. }
  17281. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Y) === BABYLON.AbstractMesh.BILLBOARDMODE_Y) {
  17282. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  17283. }
  17284. if ((this.billboardMode & BABYLON.AbstractMesh.BILLBOARDMODE_Z) === BABYLON.AbstractMesh.BILLBOARDMODE_Z) {
  17285. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  17286. }
  17287. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  17288. }
  17289. else {
  17290. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  17291. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  17292. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  17293. }
  17294. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  17295. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  17296. }
  17297. // Local world
  17298. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  17299. // Parent
  17300. if (this.parent && this.parent.getWorldMatrix) {
  17301. if (this.billboardMode !== BABYLON.AbstractMesh.BILLBOARDMODE_NONE) {
  17302. if (this._transformToBoneReferal) {
  17303. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17304. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  17305. }
  17306. else {
  17307. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  17308. }
  17309. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  17310. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  17311. this._worldMatrix.copyFrom(this._localWorld);
  17312. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  17313. }
  17314. else {
  17315. if (this._transformToBoneReferal) {
  17316. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  17317. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  17318. }
  17319. else {
  17320. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  17321. }
  17322. }
  17323. this._markSyncedWithParent();
  17324. }
  17325. else {
  17326. this._worldMatrix.copyFrom(this._localWorld);
  17327. }
  17328. // Post multiply inverse of pivotMatrix
  17329. if (this._postMultiplyPivotMatrix) {
  17330. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  17331. }
  17332. // Normal matrix
  17333. if (this.scaling.isNonUniform) {
  17334. this._updateNonUniformScalingState(true);
  17335. }
  17336. else if (this.parent && this.parent._nonUniformScaling) {
  17337. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  17338. }
  17339. else {
  17340. this._updateNonUniformScalingState(false);
  17341. }
  17342. this._afterComputeWorldMatrix();
  17343. // Absolute position
  17344. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  17345. // Callbacks
  17346. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  17347. if (!this._poseMatrix) {
  17348. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  17349. }
  17350. // Cache the determinant
  17351. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  17352. return this._worldMatrix;
  17353. };
  17354. TransformNode.prototype._afterComputeWorldMatrix = function () {
  17355. };
  17356. /**
  17357. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  17358. * @param func: callback function to add
  17359. *
  17360. * Returns the TransformNode.
  17361. */
  17362. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  17363. this.onAfterWorldMatrixUpdateObservable.add(func);
  17364. return this;
  17365. };
  17366. /**
  17367. * Removes a registered callback function.
  17368. * Returns the TransformNode.
  17369. */
  17370. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  17371. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  17372. return this;
  17373. };
  17374. /**
  17375. * Clone the current transform node
  17376. * Returns the new transform node
  17377. * @param name Name of the new clone
  17378. * @param newParent New parent for the clone
  17379. * @param doNotCloneChildren Do not clone children hierarchy
  17380. */
  17381. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  17382. var _this = this;
  17383. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  17384. result.name = name;
  17385. result.id = name;
  17386. if (newParent) {
  17387. result.parent = newParent;
  17388. }
  17389. if (!doNotCloneChildren) {
  17390. // Children
  17391. var directDescendants = this.getDescendants(true);
  17392. for (var index = 0; index < directDescendants.length; index++) {
  17393. var child = directDescendants[index];
  17394. if (child.clone) {
  17395. child.clone(name + "." + child.name, result);
  17396. }
  17397. }
  17398. }
  17399. return result;
  17400. };
  17401. TransformNode.prototype.serialize = function (currentSerializationObject) {
  17402. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  17403. serializationObject.type = this.getClassName();
  17404. // Parent
  17405. if (this.parent) {
  17406. serializationObject.parentId = this.parent.id;
  17407. }
  17408. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  17409. serializationObject.tags = BABYLON.Tags.GetTags(this);
  17410. }
  17411. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  17412. serializationObject.isEnabled = this.isEnabled();
  17413. // Parent
  17414. if (this.parent) {
  17415. serializationObject.parentId = this.parent.id;
  17416. }
  17417. return serializationObject;
  17418. };
  17419. // Statics
  17420. /**
  17421. * Returns a new TransformNode object parsed from the source provided.
  17422. * The parameter `parsedMesh` is the source.
  17423. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  17424. */
  17425. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  17426. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  17427. if (BABYLON.Tags) {
  17428. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  17429. }
  17430. if (parsedTransformNode.localMatrix) {
  17431. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  17432. }
  17433. else if (parsedTransformNode.pivotMatrix) {
  17434. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  17435. }
  17436. transformNode.setEnabled(parsedTransformNode.isEnabled);
  17437. // Parent
  17438. if (parsedTransformNode.parentId) {
  17439. transformNode._waitingParentId = parsedTransformNode.parentId;
  17440. }
  17441. return transformNode;
  17442. };
  17443. /**
  17444. * Releases resources associated with this transform node.
  17445. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17446. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17447. */
  17448. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17449. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17450. // Animations
  17451. this.getScene().stopAnimation(this);
  17452. // Remove from scene
  17453. this.getScene().removeTransformNode(this);
  17454. this.onAfterWorldMatrixUpdateObservable.clear();
  17455. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  17456. };
  17457. // Statics
  17458. TransformNode.BILLBOARDMODE_NONE = 0;
  17459. TransformNode.BILLBOARDMODE_X = 1;
  17460. TransformNode.BILLBOARDMODE_Y = 2;
  17461. TransformNode.BILLBOARDMODE_Z = 4;
  17462. TransformNode.BILLBOARDMODE_ALL = 7;
  17463. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  17464. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  17465. __decorate([
  17466. BABYLON.serializeAsVector3()
  17467. ], TransformNode.prototype, "_rotation", void 0);
  17468. __decorate([
  17469. BABYLON.serializeAsQuaternion()
  17470. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  17471. __decorate([
  17472. BABYLON.serializeAsVector3()
  17473. ], TransformNode.prototype, "_scaling", void 0);
  17474. __decorate([
  17475. BABYLON.serialize()
  17476. ], TransformNode.prototype, "billboardMode", void 0);
  17477. __decorate([
  17478. BABYLON.serialize()
  17479. ], TransformNode.prototype, "scalingDeterminant", void 0);
  17480. __decorate([
  17481. BABYLON.serialize()
  17482. ], TransformNode.prototype, "infiniteDistance", void 0);
  17483. __decorate([
  17484. BABYLON.serializeAsVector3()
  17485. ], TransformNode.prototype, "position", void 0);
  17486. return TransformNode;
  17487. }(BABYLON.Node));
  17488. BABYLON.TransformNode = TransformNode;
  17489. })(BABYLON || (BABYLON = {}));
  17490. //# sourceMappingURL=babylon.transformNode.js.map
  17491. "use strict";
  17492. var BABYLON;
  17493. (function (BABYLON) {
  17494. var AbstractMesh = /** @class */ (function (_super) {
  17495. __extends(AbstractMesh, _super);
  17496. // Constructor
  17497. function AbstractMesh(name, scene) {
  17498. if (scene === void 0) { scene = null; }
  17499. var _this = _super.call(this, name, scene, false) || this;
  17500. _this._facetNb = 0; // facet number
  17501. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  17502. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  17503. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  17504. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  17505. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  17506. _this._subDiv = {
  17507. max: 1,
  17508. X: 1,
  17509. Y: 1,
  17510. Z: 1
  17511. };
  17512. _this._facetDepthSort = false; // is the facet depth sort to be computed
  17513. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  17514. // Events
  17515. /**
  17516. * An event triggered when this mesh collides with another one
  17517. * @type {BABYLON.Observable}
  17518. */
  17519. _this.onCollideObservable = new BABYLON.Observable();
  17520. /**
  17521. * An event triggered when the collision's position changes
  17522. * @type {BABYLON.Observable}
  17523. */
  17524. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  17525. /**
  17526. * An event triggered when material is changed
  17527. * @type {BABYLON.Observable}
  17528. */
  17529. _this.onMaterialChangedObservable = new BABYLON.Observable();
  17530. // Properties
  17531. _this.definedFacingForward = true; // orientation for POV movement & rotation
  17532. /**
  17533. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  17534. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  17535. * or
  17536. * 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.
  17537. * for more info check WebGl documentations
  17538. */
  17539. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  17540. /**
  17541. * 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:
  17542. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  17543. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  17544. * 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.
  17545. */
  17546. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  17547. /**
  17548. * 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.
  17549. * The default value is -1 which means don't break the query and wait till the result.
  17550. */
  17551. _this.occlusionRetryCount = -1;
  17552. _this._occlusionInternalRetryCounter = 0;
  17553. _this._isOccluded = false;
  17554. _this._isOcclusionQueryInProgress = false;
  17555. _this._visibility = 1.0;
  17556. _this.alphaIndex = Number.MAX_VALUE;
  17557. _this.isVisible = true;
  17558. _this.isPickable = true;
  17559. _this.showBoundingBox = false;
  17560. _this.showSubMeshesBoundingBox = false;
  17561. _this.isBlocker = false;
  17562. _this.enablePointerMoveEvents = false;
  17563. _this.renderingGroupId = 0;
  17564. _this._receiveShadows = false;
  17565. _this.renderOutline = false;
  17566. _this.outlineColor = BABYLON.Color3.Red();
  17567. _this.outlineWidth = 0.02;
  17568. _this.renderOverlay = false;
  17569. _this.overlayColor = BABYLON.Color3.Red();
  17570. _this.overlayAlpha = 0.5;
  17571. _this._hasVertexAlpha = false;
  17572. _this._useVertexColors = true;
  17573. _this._computeBonesUsingShaders = true;
  17574. _this._numBoneInfluencers = 4;
  17575. _this._applyFog = true;
  17576. _this.useOctreeForRenderingSelection = true;
  17577. _this.useOctreeForPicking = true;
  17578. _this.useOctreeForCollisions = true;
  17579. _this._layerMask = 0x0FFFFFFF;
  17580. /**
  17581. * True if the mesh must be rendered in any case.
  17582. */
  17583. _this.alwaysSelectAsActiveMesh = false;
  17584. /**
  17585. * This scene's action manager
  17586. * @type {BABYLON.ActionManager}
  17587. */
  17588. _this.actionManager = null;
  17589. // Physics
  17590. _this.physicsImpostor = null;
  17591. // Collisions
  17592. _this._checkCollisions = false;
  17593. _this._collisionMask = -1;
  17594. _this._collisionGroup = -1;
  17595. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  17596. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  17597. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17598. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  17599. // Edges
  17600. _this.edgesWidth = 1;
  17601. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  17602. // Cache
  17603. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  17604. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  17605. _this._renderId = 0;
  17606. _this._intersectionsInProgress = new Array();
  17607. _this._unIndexed = false;
  17608. _this._lightSources = new Array();
  17609. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  17610. if (collidedMesh === void 0) { collidedMesh = null; }
  17611. //TODO move this to the collision coordinator!
  17612. if (_this.getScene().workerCollisions)
  17613. newPosition.multiplyInPlace(_this._collider._radius);
  17614. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  17615. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  17616. _this.position.addInPlace(_this._diffPositionForCollisions);
  17617. }
  17618. if (collidedMesh) {
  17619. _this.onCollideObservable.notifyObservers(collidedMesh);
  17620. }
  17621. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  17622. };
  17623. _this.getScene().addMesh(_this);
  17624. _this._resyncLightSources();
  17625. return _this;
  17626. }
  17627. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  17628. get: function () {
  17629. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  17630. },
  17631. enumerable: true,
  17632. configurable: true
  17633. });
  17634. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  17635. get: function () {
  17636. return BABYLON.TransformNode.BILLBOARDMODE_X;
  17637. },
  17638. enumerable: true,
  17639. configurable: true
  17640. });
  17641. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  17642. get: function () {
  17643. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  17644. },
  17645. enumerable: true,
  17646. configurable: true
  17647. });
  17648. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  17649. get: function () {
  17650. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  17651. },
  17652. enumerable: true,
  17653. configurable: true
  17654. });
  17655. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  17656. get: function () {
  17657. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  17658. },
  17659. enumerable: true,
  17660. configurable: true
  17661. });
  17662. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  17663. /**
  17664. * Read-only : the number of facets in the mesh
  17665. */
  17666. get: function () {
  17667. return this._facetNb;
  17668. },
  17669. enumerable: true,
  17670. configurable: true
  17671. });
  17672. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  17673. /**
  17674. * The number (integer) of subdivisions per axis in the partioning space
  17675. */
  17676. get: function () {
  17677. return this._partitioningSubdivisions;
  17678. },
  17679. set: function (nb) {
  17680. this._partitioningSubdivisions = nb;
  17681. },
  17682. enumerable: true,
  17683. configurable: true
  17684. });
  17685. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  17686. /**
  17687. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  17688. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  17689. */
  17690. get: function () {
  17691. return this._partitioningBBoxRatio;
  17692. },
  17693. set: function (ratio) {
  17694. this._partitioningBBoxRatio = ratio;
  17695. },
  17696. enumerable: true,
  17697. configurable: true
  17698. });
  17699. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  17700. /**
  17701. * Boolean : must the facet be depth sorted on next call to `updateFacetData()` ?
  17702. * Works only for updatable meshes.
  17703. * Doesn't work with multi-materials.
  17704. */
  17705. get: function () {
  17706. return this._facetDepthSort;
  17707. },
  17708. set: function (sort) {
  17709. this._facetDepthSort = sort;
  17710. },
  17711. enumerable: true,
  17712. configurable: true
  17713. });
  17714. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  17715. /**
  17716. * The location (Vector3) where the facet depth sort must be computed from.
  17717. * By default, the active camera position.
  17718. * Used only when facet depth sort is enabled.
  17719. */
  17720. get: function () {
  17721. return this._facetDepthSortFrom;
  17722. },
  17723. set: function (location) {
  17724. this._facetDepthSortFrom = location;
  17725. },
  17726. enumerable: true,
  17727. configurable: true
  17728. });
  17729. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  17730. /**
  17731. * Read-only boolean : is the feature facetData enabled ?
  17732. */
  17733. get: function () {
  17734. return this._facetDataEnabled;
  17735. },
  17736. enumerable: true,
  17737. configurable: true
  17738. });
  17739. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  17740. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  17741. return false;
  17742. }
  17743. this._markSubMeshesAsMiscDirty();
  17744. return true;
  17745. };
  17746. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  17747. set: function (callback) {
  17748. if (this._onCollideObserver) {
  17749. this.onCollideObservable.remove(this._onCollideObserver);
  17750. }
  17751. this._onCollideObserver = this.onCollideObservable.add(callback);
  17752. },
  17753. enumerable: true,
  17754. configurable: true
  17755. });
  17756. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  17757. set: function (callback) {
  17758. if (this._onCollisionPositionChangeObserver) {
  17759. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  17760. }
  17761. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  17762. },
  17763. enumerable: true,
  17764. configurable: true
  17765. });
  17766. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  17767. /**
  17768. * Property isOccluded : Gets or sets whether the mesh is occluded or not, it is used also to set the intial state of the mesh to be occluded or not.
  17769. */
  17770. get: function () {
  17771. return this._isOccluded;
  17772. },
  17773. set: function (value) {
  17774. this._isOccluded = value;
  17775. },
  17776. enumerable: true,
  17777. configurable: true
  17778. });
  17779. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  17780. /**
  17781. * Flag to check the progress status of the query
  17782. */
  17783. get: function () {
  17784. return this._isOcclusionQueryInProgress;
  17785. },
  17786. enumerable: true,
  17787. configurable: true
  17788. });
  17789. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  17790. /**
  17791. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17792. */
  17793. get: function () {
  17794. return this._visibility;
  17795. },
  17796. /**
  17797. * Gets or sets mesh visibility between 0 and 1 (defult is 1)
  17798. */
  17799. set: function (value) {
  17800. if (this._visibility === value) {
  17801. return;
  17802. }
  17803. this._visibility = value;
  17804. this._markSubMeshesAsMiscDirty();
  17805. },
  17806. enumerable: true,
  17807. configurable: true
  17808. });
  17809. Object.defineProperty(AbstractMesh.prototype, "material", {
  17810. get: function () {
  17811. return this._material;
  17812. },
  17813. set: function (value) {
  17814. if (this._material === value) {
  17815. return;
  17816. }
  17817. this._material = value;
  17818. if (this.onMaterialChangedObservable.hasObservers) {
  17819. this.onMaterialChangedObservable.notifyObservers(this);
  17820. }
  17821. if (!this.subMeshes) {
  17822. return;
  17823. }
  17824. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  17825. var subMesh = _a[_i];
  17826. subMesh.setEffect(null);
  17827. }
  17828. },
  17829. enumerable: true,
  17830. configurable: true
  17831. });
  17832. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  17833. get: function () {
  17834. return this._receiveShadows;
  17835. },
  17836. set: function (value) {
  17837. if (this._receiveShadows === value) {
  17838. return;
  17839. }
  17840. this._receiveShadows = value;
  17841. this._markSubMeshesAsLightDirty();
  17842. },
  17843. enumerable: true,
  17844. configurable: true
  17845. });
  17846. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  17847. get: function () {
  17848. return this._hasVertexAlpha;
  17849. },
  17850. set: function (value) {
  17851. if (this._hasVertexAlpha === value) {
  17852. return;
  17853. }
  17854. this._hasVertexAlpha = value;
  17855. this._markSubMeshesAsAttributesDirty();
  17856. this._markSubMeshesAsMiscDirty();
  17857. },
  17858. enumerable: true,
  17859. configurable: true
  17860. });
  17861. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  17862. get: function () {
  17863. return this._useVertexColors;
  17864. },
  17865. set: function (value) {
  17866. if (this._useVertexColors === value) {
  17867. return;
  17868. }
  17869. this._useVertexColors = value;
  17870. this._markSubMeshesAsAttributesDirty();
  17871. },
  17872. enumerable: true,
  17873. configurable: true
  17874. });
  17875. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  17876. get: function () {
  17877. return this._computeBonesUsingShaders;
  17878. },
  17879. set: function (value) {
  17880. if (this._computeBonesUsingShaders === value) {
  17881. return;
  17882. }
  17883. this._computeBonesUsingShaders = value;
  17884. this._markSubMeshesAsAttributesDirty();
  17885. },
  17886. enumerable: true,
  17887. configurable: true
  17888. });
  17889. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  17890. get: function () {
  17891. return this._numBoneInfluencers;
  17892. },
  17893. set: function (value) {
  17894. if (this._numBoneInfluencers === value) {
  17895. return;
  17896. }
  17897. this._numBoneInfluencers = value;
  17898. this._markSubMeshesAsAttributesDirty();
  17899. },
  17900. enumerable: true,
  17901. configurable: true
  17902. });
  17903. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  17904. get: function () {
  17905. return this._applyFog;
  17906. },
  17907. set: function (value) {
  17908. if (this._applyFog === value) {
  17909. return;
  17910. }
  17911. this._applyFog = value;
  17912. this._markSubMeshesAsMiscDirty();
  17913. },
  17914. enumerable: true,
  17915. configurable: true
  17916. });
  17917. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  17918. get: function () {
  17919. return this._layerMask;
  17920. },
  17921. set: function (value) {
  17922. if (value === this._layerMask) {
  17923. return;
  17924. }
  17925. this._layerMask = value;
  17926. this._resyncLightSources();
  17927. },
  17928. enumerable: true,
  17929. configurable: true
  17930. });
  17931. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  17932. get: function () {
  17933. return this._collisionMask;
  17934. },
  17935. set: function (mask) {
  17936. this._collisionMask = !isNaN(mask) ? mask : -1;
  17937. },
  17938. enumerable: true,
  17939. configurable: true
  17940. });
  17941. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  17942. get: function () {
  17943. return this._collisionGroup;
  17944. },
  17945. set: function (mask) {
  17946. this._collisionGroup = !isNaN(mask) ? mask : -1;
  17947. },
  17948. enumerable: true,
  17949. configurable: true
  17950. });
  17951. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  17952. get: function () {
  17953. return null;
  17954. },
  17955. enumerable: true,
  17956. configurable: true
  17957. });
  17958. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  17959. get: function () {
  17960. return this._skeleton;
  17961. },
  17962. set: function (value) {
  17963. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  17964. this._skeleton._unregisterMeshWithPoseMatrix(this);
  17965. }
  17966. if (value && value.needInitialSkinMatrix) {
  17967. value._registerMeshWithPoseMatrix(this);
  17968. }
  17969. this._skeleton = value;
  17970. if (!this._skeleton) {
  17971. this._bonesTransformMatrices = null;
  17972. }
  17973. this._markSubMeshesAsAttributesDirty();
  17974. },
  17975. enumerable: true,
  17976. configurable: true
  17977. });
  17978. /**
  17979. * Returns the string "AbstractMesh"
  17980. */
  17981. AbstractMesh.prototype.getClassName = function () {
  17982. return "AbstractMesh";
  17983. };
  17984. /**
  17985. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  17986. */
  17987. AbstractMesh.prototype.toString = function (fullDetails) {
  17988. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  17989. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  17990. if (this._skeleton) {
  17991. ret += ", skeleton: " + this._skeleton.name;
  17992. }
  17993. if (fullDetails) {
  17994. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  17995. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  17996. }
  17997. return ret;
  17998. };
  17999. AbstractMesh.prototype._rebuild = function () {
  18000. if (this._occlusionQuery) {
  18001. this._occlusionQuery = null;
  18002. }
  18003. if (this._edgesRenderer) {
  18004. this._edgesRenderer._rebuild();
  18005. }
  18006. if (!this.subMeshes) {
  18007. return;
  18008. }
  18009. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  18010. var subMesh = _a[_i];
  18011. subMesh._rebuild();
  18012. }
  18013. };
  18014. AbstractMesh.prototype._resyncLightSources = function () {
  18015. this._lightSources.length = 0;
  18016. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  18017. var light = _a[_i];
  18018. if (!light.isEnabled()) {
  18019. continue;
  18020. }
  18021. if (light.canAffectMesh(this)) {
  18022. this._lightSources.push(light);
  18023. }
  18024. }
  18025. this._markSubMeshesAsLightDirty();
  18026. };
  18027. AbstractMesh.prototype._resyncLighSource = function (light) {
  18028. var isIn = light.isEnabled() && light.canAffectMesh(this);
  18029. var index = this._lightSources.indexOf(light);
  18030. if (index === -1) {
  18031. if (!isIn) {
  18032. return;
  18033. }
  18034. this._lightSources.push(light);
  18035. }
  18036. else {
  18037. if (isIn) {
  18038. return;
  18039. }
  18040. this._lightSources.splice(index, 1);
  18041. }
  18042. this._markSubMeshesAsLightDirty();
  18043. };
  18044. AbstractMesh.prototype._removeLightSource = function (light) {
  18045. var index = this._lightSources.indexOf(light);
  18046. if (index === -1) {
  18047. return;
  18048. }
  18049. this._lightSources.splice(index, 1);
  18050. this._markSubMeshesAsLightDirty();
  18051. };
  18052. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  18053. if (!this.subMeshes) {
  18054. return;
  18055. }
  18056. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  18057. var subMesh = _a[_i];
  18058. if (subMesh._materialDefines) {
  18059. func(subMesh._materialDefines);
  18060. }
  18061. }
  18062. };
  18063. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  18064. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  18065. };
  18066. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  18067. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  18068. };
  18069. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  18070. if (!this.subMeshes) {
  18071. return;
  18072. }
  18073. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  18074. var subMesh = _a[_i];
  18075. var material = subMesh.getMaterial();
  18076. if (material) {
  18077. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  18078. }
  18079. }
  18080. };
  18081. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  18082. /**
  18083. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18084. * Default : (1.0, 1.0, 1.0)
  18085. */
  18086. get: function () {
  18087. return this._scaling;
  18088. },
  18089. /**
  18090. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18091. * Default : (1.0, 1.0, 1.0)
  18092. */
  18093. set: function (newScaling) {
  18094. this._scaling = newScaling;
  18095. if (this.physicsImpostor) {
  18096. this.physicsImpostor.forceUpdate();
  18097. }
  18098. },
  18099. enumerable: true,
  18100. configurable: true
  18101. });
  18102. // Methods
  18103. /**
  18104. * Disables the mesh edger rendering mode.
  18105. * Returns the AbstractMesh.
  18106. */
  18107. AbstractMesh.prototype.disableEdgesRendering = function () {
  18108. if (this._edgesRenderer) {
  18109. this._edgesRenderer.dispose();
  18110. this._edgesRenderer = null;
  18111. }
  18112. return this;
  18113. };
  18114. /**
  18115. * Enables the edge rendering mode on the mesh.
  18116. * This mode makes the mesh edges visible.
  18117. * Returns the AbstractMesh.
  18118. */
  18119. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  18120. if (epsilon === void 0) { epsilon = 0.95; }
  18121. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  18122. this.disableEdgesRendering();
  18123. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  18124. return this;
  18125. };
  18126. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  18127. /**
  18128. * Returns true if the mesh is blocked. Used by the class Mesh.
  18129. * Returns the boolean `false` by default.
  18130. */
  18131. get: function () {
  18132. return false;
  18133. },
  18134. enumerable: true,
  18135. configurable: true
  18136. });
  18137. /**
  18138. * Returns the mesh itself by default, used by the class Mesh.
  18139. * Returned type : AbstractMesh
  18140. */
  18141. AbstractMesh.prototype.getLOD = function (camera) {
  18142. return this;
  18143. };
  18144. /**
  18145. * Returns 0 by default, used by the class Mesh.
  18146. * Returns an integer.
  18147. */
  18148. AbstractMesh.prototype.getTotalVertices = function () {
  18149. return 0;
  18150. };
  18151. /**
  18152. * Returns null by default, used by the class Mesh.
  18153. * Returned type : integer array
  18154. */
  18155. AbstractMesh.prototype.getIndices = function () {
  18156. return null;
  18157. };
  18158. /**
  18159. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  18160. * Returned type : float array or Float32Array
  18161. */
  18162. AbstractMesh.prototype.getVerticesData = function (kind) {
  18163. return null;
  18164. };
  18165. /**
  18166. * Sets the vertex data of the mesh geometry for the requested `kind`.
  18167. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  18168. * The `data` are either a numeric array either a Float32Array.
  18169. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  18170. * 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).
  18171. * Note that a new underlying VertexBuffer object is created each call.
  18172. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  18173. *
  18174. * Possible `kind` values :
  18175. * - BABYLON.VertexBuffer.PositionKind
  18176. * - BABYLON.VertexBuffer.UVKind
  18177. * - BABYLON.VertexBuffer.UV2Kind
  18178. * - BABYLON.VertexBuffer.UV3Kind
  18179. * - BABYLON.VertexBuffer.UV4Kind
  18180. * - BABYLON.VertexBuffer.UV5Kind
  18181. * - BABYLON.VertexBuffer.UV6Kind
  18182. * - BABYLON.VertexBuffer.ColorKind
  18183. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18184. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18185. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18186. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18187. *
  18188. * Returns the Mesh.
  18189. */
  18190. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  18191. return this;
  18192. };
  18193. /**
  18194. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  18195. * If the mesh has no geometry, it is simply returned as it is.
  18196. * The `data` are either a numeric array either a Float32Array.
  18197. * No new underlying VertexBuffer object is created.
  18198. * 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.
  18199. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  18200. *
  18201. * Possible `kind` values :
  18202. * - BABYLON.VertexBuffer.PositionKind
  18203. * - BABYLON.VertexBuffer.UVKind
  18204. * - BABYLON.VertexBuffer.UV2Kind
  18205. * - BABYLON.VertexBuffer.UV3Kind
  18206. * - BABYLON.VertexBuffer.UV4Kind
  18207. * - BABYLON.VertexBuffer.UV5Kind
  18208. * - BABYLON.VertexBuffer.UV6Kind
  18209. * - BABYLON.VertexBuffer.ColorKind
  18210. * - BABYLON.VertexBuffer.MatricesIndicesKind
  18211. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  18212. * - BABYLON.VertexBuffer.MatricesWeightsKind
  18213. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  18214. *
  18215. * Returns the Mesh.
  18216. */
  18217. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  18218. return this;
  18219. };
  18220. /**
  18221. * Sets the mesh indices.
  18222. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  18223. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  18224. * This method creates a new index buffer each call.
  18225. * Returns the Mesh.
  18226. */
  18227. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  18228. return this;
  18229. };
  18230. /** Returns false by default, used by the class Mesh.
  18231. * Returns a boolean
  18232. */
  18233. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  18234. return false;
  18235. };
  18236. /**
  18237. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  18238. * Returns a BoundingInfo
  18239. */
  18240. AbstractMesh.prototype.getBoundingInfo = function () {
  18241. if (this._masterMesh) {
  18242. return this._masterMesh.getBoundingInfo();
  18243. }
  18244. if (!this._boundingInfo) {
  18245. // this._boundingInfo is being created here
  18246. this._updateBoundingInfo();
  18247. }
  18248. // cannot be null.
  18249. return this._boundingInfo;
  18250. };
  18251. /**
  18252. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units).
  18253. * @param includeDescendants Take the hierarchy's bounding box instead of the mesh's bounding box.
  18254. */
  18255. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  18256. if (includeDescendants === void 0) { includeDescendants = true; }
  18257. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  18258. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  18259. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  18260. if (maxDimension === 0) {
  18261. return this;
  18262. }
  18263. var scale = 1 / maxDimension;
  18264. this.scaling.scaleInPlace(scale);
  18265. return this;
  18266. };
  18267. /**
  18268. * Sets a mesh new object BoundingInfo.
  18269. * Returns the AbstractMesh.
  18270. */
  18271. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  18272. this._boundingInfo = boundingInfo;
  18273. return this;
  18274. };
  18275. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  18276. get: function () {
  18277. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  18278. },
  18279. enumerable: true,
  18280. configurable: true
  18281. });
  18282. AbstractMesh.prototype._preActivate = function () {
  18283. };
  18284. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  18285. };
  18286. AbstractMesh.prototype._activate = function (renderId) {
  18287. this._renderId = renderId;
  18288. };
  18289. /**
  18290. * Returns the latest update of the World matrix
  18291. * Returns a Matrix.
  18292. */
  18293. AbstractMesh.prototype.getWorldMatrix = function () {
  18294. if (this._masterMesh) {
  18295. return this._masterMesh.getWorldMatrix();
  18296. }
  18297. return _super.prototype.getWorldMatrix.call(this);
  18298. };
  18299. /**
  18300. * Returns the latest update of the World matrix determinant.
  18301. */
  18302. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  18303. if (this._masterMesh) {
  18304. return this._masterMesh._getWorldMatrixDeterminant();
  18305. }
  18306. return _super.prototype._getWorldMatrixDeterminant.call(this);
  18307. };
  18308. // ================================== Point of View Movement =================================
  18309. /**
  18310. * Perform relative position change from the point of view of behind the front of the mesh.
  18311. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18312. * Supports definition of mesh facing forward or backward.
  18313. * @param {number} amountRight
  18314. * @param {number} amountUp
  18315. * @param {number} amountForward
  18316. *
  18317. * Returns the AbstractMesh.
  18318. */
  18319. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  18320. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  18321. return this;
  18322. };
  18323. /**
  18324. * Calculate relative position change from the point of view of behind the front of the mesh.
  18325. * This is performed taking into account the meshes current rotation, so you do not have to care.
  18326. * Supports definition of mesh facing forward or backward.
  18327. * @param {number} amountRight
  18328. * @param {number} amountUp
  18329. * @param {number} amountForward
  18330. *
  18331. * Returns a new Vector3.
  18332. */
  18333. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  18334. var rotMatrix = new BABYLON.Matrix();
  18335. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18336. rotQuaternion.toRotationMatrix(rotMatrix);
  18337. var translationDelta = BABYLON.Vector3.Zero();
  18338. var defForwardMult = this.definedFacingForward ? -1 : 1;
  18339. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  18340. return translationDelta;
  18341. };
  18342. // ================================== Point of View Rotation =================================
  18343. /**
  18344. * Perform relative rotation change from the point of view of behind the front of the mesh.
  18345. * Supports definition of mesh facing forward or backward.
  18346. * @param {number} flipBack
  18347. * @param {number} twirlClockwise
  18348. * @param {number} tiltRight
  18349. *
  18350. * Returns the AbstractMesh.
  18351. */
  18352. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18353. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  18354. return this;
  18355. };
  18356. /**
  18357. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  18358. * Supports definition of mesh facing forward or backward.
  18359. * @param {number} flipBack
  18360. * @param {number} twirlClockwise
  18361. * @param {number} tiltRight
  18362. *
  18363. * Returns a new Vector3.
  18364. */
  18365. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  18366. var defForwardMult = this.definedFacingForward ? 1 : -1;
  18367. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  18368. };
  18369. /**
  18370. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  18371. * @param includeDescendants Include bounding info from descendants as well (true by default).
  18372. */
  18373. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  18374. if (includeDescendants === void 0) { includeDescendants = true; }
  18375. this.computeWorldMatrix(true);
  18376. var min;
  18377. var max;
  18378. var boundingInfo = this.getBoundingInfo();
  18379. if (!this.subMeshes) {
  18380. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18381. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18382. }
  18383. else {
  18384. min = boundingInfo.boundingBox.minimumWorld;
  18385. max = boundingInfo.boundingBox.maximumWorld;
  18386. }
  18387. if (includeDescendants) {
  18388. var descendants = this.getDescendants(false);
  18389. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  18390. var descendant = descendants_1[_i];
  18391. var childMesh = descendant;
  18392. childMesh.computeWorldMatrix(true);
  18393. //make sure we have the needed params to get mix and max
  18394. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  18395. continue;
  18396. }
  18397. var childBoundingInfo = childMesh.getBoundingInfo();
  18398. var boundingBox = childBoundingInfo.boundingBox;
  18399. var minBox = boundingBox.minimumWorld;
  18400. var maxBox = boundingBox.maximumWorld;
  18401. BABYLON.Tools.CheckExtends(minBox, min, max);
  18402. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18403. }
  18404. }
  18405. return {
  18406. min: min,
  18407. max: max
  18408. };
  18409. };
  18410. /**
  18411. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  18412. * Returns the AbstractMesh.
  18413. */
  18414. AbstractMesh.prototype._updateBoundingInfo = function () {
  18415. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  18416. this._boundingInfo.update(this.worldMatrixFromCache);
  18417. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  18418. return this;
  18419. };
  18420. /**
  18421. * Update a mesh's children BoundingInfo objects only.
  18422. * Returns the AbstractMesh.
  18423. */
  18424. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  18425. if (!this.subMeshes) {
  18426. return this;
  18427. }
  18428. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  18429. var subMesh = this.subMeshes[subIndex];
  18430. if (!subMesh.IsGlobal) {
  18431. subMesh.updateBoundingInfo(matrix);
  18432. }
  18433. }
  18434. return this;
  18435. };
  18436. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  18437. // Bounding info
  18438. this._updateBoundingInfo();
  18439. };
  18440. /**
  18441. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  18442. * A mesh is in the frustum if its bounding box intersects the frustum.
  18443. * Boolean returned.
  18444. */
  18445. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  18446. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  18447. };
  18448. /**
  18449. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  18450. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  18451. * Boolean returned.
  18452. */
  18453. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18454. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  18455. ;
  18456. };
  18457. /**
  18458. * True if the mesh intersects another mesh or a SolidParticle object.
  18459. * 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)
  18460. * includeDescendants can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  18461. * Returns a boolean.
  18462. */
  18463. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  18464. if (precise === void 0) { precise = false; }
  18465. if (!this._boundingInfo || !mesh._boundingInfo) {
  18466. return false;
  18467. }
  18468. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  18469. return true;
  18470. }
  18471. if (includeDescendants) {
  18472. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  18473. var child = _a[_i];
  18474. if (child.intersectsMesh(mesh, precise, true)) {
  18475. return true;
  18476. }
  18477. }
  18478. }
  18479. return false;
  18480. };
  18481. /**
  18482. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  18483. * Returns a boolean.
  18484. */
  18485. AbstractMesh.prototype.intersectsPoint = function (point) {
  18486. if (!this._boundingInfo) {
  18487. return false;
  18488. }
  18489. return this._boundingInfo.intersectsPoint(point);
  18490. };
  18491. AbstractMesh.prototype.getPhysicsImpostor = function () {
  18492. return this.physicsImpostor;
  18493. };
  18494. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  18495. if (camera === void 0) { camera = null; }
  18496. if (!camera) {
  18497. camera = this.getScene().activeCamera;
  18498. }
  18499. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  18500. };
  18501. /**
  18502. * Returns the distance from the mesh to the active camera.
  18503. * Returns a float.
  18504. */
  18505. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  18506. if (camera === void 0) { camera = null; }
  18507. if (!camera) {
  18508. camera = this.getScene().activeCamera;
  18509. }
  18510. return this.absolutePosition.subtract(camera.position).length();
  18511. };
  18512. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  18513. if (!this.physicsImpostor) {
  18514. return this;
  18515. }
  18516. this.physicsImpostor.applyImpulse(force, contactPoint);
  18517. return this;
  18518. };
  18519. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  18520. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  18521. return this;
  18522. }
  18523. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  18524. mainPivot: pivot1,
  18525. connectedPivot: pivot2,
  18526. nativeParams: options
  18527. });
  18528. return this;
  18529. };
  18530. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  18531. // Collisions
  18532. /**
  18533. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  18534. * Default `false`.
  18535. */
  18536. get: function () {
  18537. return this._checkCollisions;
  18538. },
  18539. set: function (collisionEnabled) {
  18540. this._checkCollisions = collisionEnabled;
  18541. if (this.getScene().workerCollisions) {
  18542. this.getScene().collisionCoordinator.onMeshUpdated(this);
  18543. }
  18544. },
  18545. enumerable: true,
  18546. configurable: true
  18547. });
  18548. Object.defineProperty(AbstractMesh.prototype, "collider", {
  18549. /**
  18550. * Gets Collider object used to compute collisions (not physics)
  18551. */
  18552. get: function () {
  18553. return this._collider;
  18554. },
  18555. enumerable: true,
  18556. configurable: true
  18557. });
  18558. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  18559. var globalPosition = this.getAbsolutePosition();
  18560. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  18561. if (!this._collider) {
  18562. this._collider = new BABYLON.Collider();
  18563. }
  18564. this._collider._radius = this.ellipsoid;
  18565. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  18566. return this;
  18567. };
  18568. // Submeshes octree
  18569. /**
  18570. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  18571. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  18572. * Returns an Octree of submeshes.
  18573. */
  18574. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  18575. if (maxCapacity === void 0) { maxCapacity = 64; }
  18576. if (maxDepth === void 0) { maxDepth = 2; }
  18577. if (!this._submeshesOctree) {
  18578. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  18579. }
  18580. this.computeWorldMatrix(true);
  18581. var boundingInfo = this.getBoundingInfo();
  18582. // Update octree
  18583. var bbox = boundingInfo.boundingBox;
  18584. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  18585. return this._submeshesOctree;
  18586. };
  18587. // Collisions
  18588. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  18589. this._generatePointsArray();
  18590. if (!this._positions) {
  18591. return this;
  18592. }
  18593. // Transformation
  18594. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  18595. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  18596. subMesh._lastColliderWorldVertices = [];
  18597. subMesh._trianglePlanes = [];
  18598. var start = subMesh.verticesStart;
  18599. var end = (subMesh.verticesStart + subMesh.verticesCount);
  18600. for (var i = start; i < end; i++) {
  18601. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  18602. }
  18603. }
  18604. // Collide
  18605. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  18606. if (collider.collisionFound) {
  18607. collider.collidedMesh = this;
  18608. }
  18609. return this;
  18610. };
  18611. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  18612. var subMeshes;
  18613. var len;
  18614. // Octrees
  18615. if (this._submeshesOctree && this.useOctreeForCollisions) {
  18616. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  18617. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  18618. len = intersections.length;
  18619. subMeshes = intersections.data;
  18620. }
  18621. else {
  18622. subMeshes = this.subMeshes;
  18623. len = subMeshes.length;
  18624. }
  18625. for (var index = 0; index < len; index++) {
  18626. var subMesh = subMeshes[index];
  18627. // Bounding test
  18628. if (len > 1 && !subMesh._checkCollision(collider))
  18629. continue;
  18630. this._collideForSubMesh(subMesh, transformMatrix, collider);
  18631. }
  18632. return this;
  18633. };
  18634. AbstractMesh.prototype._checkCollision = function (collider) {
  18635. // Bounding box test
  18636. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  18637. return this;
  18638. // Transformation matrix
  18639. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  18640. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  18641. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  18642. return this;
  18643. };
  18644. // Picking
  18645. AbstractMesh.prototype._generatePointsArray = function () {
  18646. return false;
  18647. };
  18648. /**
  18649. * Checks if the passed Ray intersects with the mesh.
  18650. * Returns an object PickingInfo.
  18651. */
  18652. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  18653. var pickingInfo = new BABYLON.PickingInfo();
  18654. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  18655. return pickingInfo;
  18656. }
  18657. if (!this._generatePointsArray()) {
  18658. return pickingInfo;
  18659. }
  18660. var intersectInfo = null;
  18661. // Octrees
  18662. var subMeshes;
  18663. var len;
  18664. if (this._submeshesOctree && this.useOctreeForPicking) {
  18665. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  18666. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  18667. len = intersections.length;
  18668. subMeshes = intersections.data;
  18669. }
  18670. else {
  18671. subMeshes = this.subMeshes;
  18672. len = subMeshes.length;
  18673. }
  18674. for (var index = 0; index < len; index++) {
  18675. var subMesh = subMeshes[index];
  18676. // Bounding test
  18677. if (len > 1 && !subMesh.canIntersects(ray))
  18678. continue;
  18679. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  18680. if (currentIntersectInfo) {
  18681. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  18682. intersectInfo = currentIntersectInfo;
  18683. intersectInfo.subMeshId = index;
  18684. if (fastCheck) {
  18685. break;
  18686. }
  18687. }
  18688. }
  18689. }
  18690. if (intersectInfo) {
  18691. // Get picked point
  18692. var world = this.getWorldMatrix();
  18693. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  18694. var direction = ray.direction.clone();
  18695. direction = direction.scale(intersectInfo.distance);
  18696. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  18697. var pickedPoint = worldOrigin.add(worldDirection);
  18698. // Return result
  18699. pickingInfo.hit = true;
  18700. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  18701. pickingInfo.pickedPoint = pickedPoint;
  18702. pickingInfo.pickedMesh = this;
  18703. pickingInfo.bu = intersectInfo.bu || 0;
  18704. pickingInfo.bv = intersectInfo.bv || 0;
  18705. pickingInfo.faceId = intersectInfo.faceId;
  18706. pickingInfo.subMeshId = intersectInfo.subMeshId;
  18707. return pickingInfo;
  18708. }
  18709. return pickingInfo;
  18710. };
  18711. /**
  18712. * Clones the mesh, used by the class Mesh.
  18713. * Just returns `null` for an AbstractMesh.
  18714. */
  18715. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  18716. return null;
  18717. };
  18718. /**
  18719. * Disposes all the mesh submeshes.
  18720. * Returns the AbstractMesh.
  18721. */
  18722. AbstractMesh.prototype.releaseSubMeshes = function () {
  18723. if (this.subMeshes) {
  18724. while (this.subMeshes.length) {
  18725. this.subMeshes[0].dispose();
  18726. }
  18727. }
  18728. else {
  18729. this.subMeshes = new Array();
  18730. }
  18731. return this;
  18732. };
  18733. /**
  18734. * Releases resources associated with this abstract mesh.
  18735. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18736. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18737. */
  18738. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18739. var _this = this;
  18740. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18741. var index;
  18742. // Smart Array Retainers.
  18743. this.getScene().freeActiveMeshes();
  18744. this.getScene().freeRenderingGroups();
  18745. // Action manager
  18746. if (this.actionManager !== undefined && this.actionManager !== null) {
  18747. this.actionManager.dispose();
  18748. this.actionManager = null;
  18749. }
  18750. // Skeleton
  18751. this.skeleton = null;
  18752. // Physics
  18753. if (this.physicsImpostor) {
  18754. this.physicsImpostor.dispose();
  18755. }
  18756. // Intersections in progress
  18757. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  18758. var other = this._intersectionsInProgress[index];
  18759. var pos = other._intersectionsInProgress.indexOf(this);
  18760. other._intersectionsInProgress.splice(pos, 1);
  18761. }
  18762. this._intersectionsInProgress = [];
  18763. // Lights
  18764. var lights = this.getScene().lights;
  18765. lights.forEach(function (light) {
  18766. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  18767. if (meshIndex !== -1) {
  18768. light.includedOnlyMeshes.splice(meshIndex, 1);
  18769. }
  18770. meshIndex = light.excludedMeshes.indexOf(_this);
  18771. if (meshIndex !== -1) {
  18772. light.excludedMeshes.splice(meshIndex, 1);
  18773. }
  18774. // Shadow generators
  18775. var generator = light.getShadowGenerator();
  18776. if (generator) {
  18777. var shadowMap = generator.getShadowMap();
  18778. if (shadowMap && shadowMap.renderList) {
  18779. meshIndex = shadowMap.renderList.indexOf(_this);
  18780. if (meshIndex !== -1) {
  18781. shadowMap.renderList.splice(meshIndex, 1);
  18782. }
  18783. }
  18784. }
  18785. });
  18786. // Edges
  18787. if (this._edgesRenderer) {
  18788. this._edgesRenderer.dispose();
  18789. this._edgesRenderer = null;
  18790. }
  18791. // SubMeshes
  18792. if (this.getClassName() !== "InstancedMesh") {
  18793. this.releaseSubMeshes();
  18794. }
  18795. // Octree
  18796. var sceneOctree = this.getScene().selectionOctree;
  18797. if (sceneOctree !== undefined && sceneOctree !== null) {
  18798. var index = sceneOctree.dynamicContent.indexOf(this);
  18799. if (index !== -1) {
  18800. sceneOctree.dynamicContent.splice(index, 1);
  18801. }
  18802. }
  18803. // Query
  18804. var engine = this.getScene().getEngine();
  18805. if (this._occlusionQuery) {
  18806. this._isOcclusionQueryInProgress = false;
  18807. engine.deleteQuery(this._occlusionQuery);
  18808. this._occlusionQuery = null;
  18809. }
  18810. // Engine
  18811. engine.wipeCaches();
  18812. // Remove from scene
  18813. this.getScene().removeMesh(this);
  18814. if (disposeMaterialAndTextures) {
  18815. if (this.material) {
  18816. this.material.dispose(false, true);
  18817. }
  18818. }
  18819. if (!doNotRecurse) {
  18820. // Particles
  18821. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  18822. if (this.getScene().particleSystems[index].emitter === this) {
  18823. this.getScene().particleSystems[index].dispose();
  18824. index--;
  18825. }
  18826. }
  18827. }
  18828. // facet data
  18829. if (this._facetDataEnabled) {
  18830. this.disableFacetData();
  18831. }
  18832. this.onAfterWorldMatrixUpdateObservable.clear();
  18833. this.onCollideObservable.clear();
  18834. this.onCollisionPositionChangeObservable.clear();
  18835. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  18836. };
  18837. /**
  18838. * Adds the passed mesh as a child to the current mesh.
  18839. * Returns the AbstractMesh.
  18840. */
  18841. AbstractMesh.prototype.addChild = function (mesh) {
  18842. mesh.setParent(this);
  18843. return this;
  18844. };
  18845. /**
  18846. * Removes the passed mesh from the current mesh children list.
  18847. * Returns the AbstractMesh.
  18848. */
  18849. AbstractMesh.prototype.removeChild = function (mesh) {
  18850. mesh.setParent(null);
  18851. return this;
  18852. };
  18853. // Facet data
  18854. /**
  18855. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  18856. * Returns the AbstractMesh.
  18857. */
  18858. AbstractMesh.prototype._initFacetData = function () {
  18859. if (!this._facetNormals) {
  18860. this._facetNormals = new Array();
  18861. }
  18862. if (!this._facetPositions) {
  18863. this._facetPositions = new Array();
  18864. }
  18865. if (!this._facetPartitioning) {
  18866. this._facetPartitioning = new Array();
  18867. }
  18868. this._facetNb = (this.getIndices().length / 3) | 0;
  18869. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  18870. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  18871. for (var f = 0; f < this._facetNb; f++) {
  18872. this._facetNormals[f] = BABYLON.Vector3.Zero();
  18873. this._facetPositions[f] = BABYLON.Vector3.Zero();
  18874. }
  18875. this._facetDataEnabled = true;
  18876. return this;
  18877. };
  18878. /**
  18879. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  18880. * This method can be called within the render loop.
  18881. * 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.
  18882. * Returns the AbstractMesh.
  18883. */
  18884. AbstractMesh.prototype.updateFacetData = function () {
  18885. if (!this._facetDataEnabled) {
  18886. this._initFacetData();
  18887. }
  18888. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  18889. var indices = this.getIndices();
  18890. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  18891. var bInfo = this.getBoundingInfo();
  18892. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  18893. // init arrays, matrix and sort function on first call
  18894. this._facetDepthSortEnabled = true;
  18895. if (indices instanceof Uint16Array) {
  18896. this._depthSortedIndices = new Uint16Array(indices);
  18897. }
  18898. else if (indices instanceof Uint32Array) {
  18899. this._depthSortedIndices = new Uint32Array(indices);
  18900. }
  18901. else {
  18902. var needs32bits = false;
  18903. for (var i = 0; i < indices.length; i++) {
  18904. if (indices[i] > 65535) {
  18905. needs32bits = true;
  18906. break;
  18907. }
  18908. }
  18909. if (needs32bits) {
  18910. this._depthSortedIndices = new Uint32Array(indices);
  18911. }
  18912. else {
  18913. this._depthSortedIndices = new Uint16Array(indices);
  18914. }
  18915. }
  18916. this._facetDepthSortFunction = function (f1, f2) {
  18917. return (f2.sqDistance - f1.sqDistance);
  18918. };
  18919. if (!this._facetDepthSortFrom) {
  18920. var camera = this.getScene().activeCamera;
  18921. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  18922. }
  18923. this._depthSortedFacets = [];
  18924. for (var f = 0; f < this._facetNb; f++) {
  18925. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  18926. this._depthSortedFacets.push(depthSortedFacet);
  18927. }
  18928. this._invertedMatrix = BABYLON.Matrix.Identity();
  18929. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  18930. }
  18931. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  18932. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  18933. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  18934. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  18935. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  18936. this._subDiv.max = this._partitioningSubdivisions;
  18937. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  18938. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  18939. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  18940. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  18941. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  18942. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  18943. // set the parameters for ComputeNormals()
  18944. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  18945. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  18946. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  18947. this._facetParameters.bInfo = bInfo;
  18948. this._facetParameters.bbSize = this._bbSize;
  18949. this._facetParameters.subDiv = this._subDiv;
  18950. this._facetParameters.ratio = this.partitioningBBoxRatio;
  18951. this._facetParameters.depthSort = this._facetDepthSort;
  18952. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18953. this.computeWorldMatrix(true);
  18954. this._worldMatrix.invertToRef(this._invertedMatrix);
  18955. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  18956. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  18957. }
  18958. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  18959. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  18960. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  18961. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  18962. var l = (this._depthSortedIndices.length / 3) | 0;
  18963. for (var f = 0; f < l; f++) {
  18964. var sind = this._depthSortedFacets[f].ind;
  18965. this._depthSortedIndices[f * 3] = indices[sind];
  18966. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  18967. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  18968. }
  18969. this.updateIndices(this._depthSortedIndices);
  18970. }
  18971. return this;
  18972. };
  18973. /**
  18974. * Returns the facetLocalNormals array.
  18975. * The normals are expressed in the mesh local space.
  18976. */
  18977. AbstractMesh.prototype.getFacetLocalNormals = function () {
  18978. if (!this._facetNormals) {
  18979. this.updateFacetData();
  18980. }
  18981. return this._facetNormals;
  18982. };
  18983. /**
  18984. * Returns the facetLocalPositions array.
  18985. * The facet positions are expressed in the mesh local space.
  18986. */
  18987. AbstractMesh.prototype.getFacetLocalPositions = function () {
  18988. if (!this._facetPositions) {
  18989. this.updateFacetData();
  18990. }
  18991. return this._facetPositions;
  18992. };
  18993. /**
  18994. * Returns the facetLocalPartioning array.
  18995. */
  18996. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  18997. if (!this._facetPartitioning) {
  18998. this.updateFacetData();
  18999. }
  19000. return this._facetPartitioning;
  19001. };
  19002. /**
  19003. * Returns the i-th facet position in the world system.
  19004. * This method allocates a new Vector3 per call.
  19005. */
  19006. AbstractMesh.prototype.getFacetPosition = function (i) {
  19007. var pos = BABYLON.Vector3.Zero();
  19008. this.getFacetPositionToRef(i, pos);
  19009. return pos;
  19010. };
  19011. /**
  19012. * Sets the reference Vector3 with the i-th facet position in the world system.
  19013. * Returns the AbstractMesh.
  19014. */
  19015. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  19016. var localPos = (this.getFacetLocalPositions())[i];
  19017. var world = this.getWorldMatrix();
  19018. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  19019. return this;
  19020. };
  19021. /**
  19022. * Returns the i-th facet normal in the world system.
  19023. * This method allocates a new Vector3 per call.
  19024. */
  19025. AbstractMesh.prototype.getFacetNormal = function (i) {
  19026. var norm = BABYLON.Vector3.Zero();
  19027. this.getFacetNormalToRef(i, norm);
  19028. return norm;
  19029. };
  19030. /**
  19031. * Sets the reference Vector3 with the i-th facet normal in the world system.
  19032. * Returns the AbstractMesh.
  19033. */
  19034. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  19035. var localNorm = (this.getFacetLocalNormals())[i];
  19036. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  19037. return this;
  19038. };
  19039. /**
  19040. * 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).
  19041. */
  19042. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  19043. var bInfo = this.getBoundingInfo();
  19044. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  19045. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  19046. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  19047. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  19048. return null;
  19049. }
  19050. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  19051. };
  19052. /**
  19053. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  19054. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  19055. * If checkFace is true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned.
  19056. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  19057. * 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.
  19058. */
  19059. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  19060. if (checkFace === void 0) { checkFace = false; }
  19061. if (facing === void 0) { facing = true; }
  19062. var world = this.getWorldMatrix();
  19063. var invMat = BABYLON.Tmp.Matrix[5];
  19064. world.invertToRef(invMat);
  19065. var invVect = BABYLON.Tmp.Vector3[8];
  19066. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  19067. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  19068. if (projected) {
  19069. // tranform the local computed projected vector to world coordinates
  19070. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  19071. }
  19072. return closest;
  19073. };
  19074. /**
  19075. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  19076. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  19077. * If checkFace is true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned.
  19078. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  19079. * 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.
  19080. */
  19081. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  19082. if (checkFace === void 0) { checkFace = false; }
  19083. if (facing === void 0) { facing = true; }
  19084. var closest = null;
  19085. var tmpx = 0.0;
  19086. var tmpy = 0.0;
  19087. var tmpz = 0.0;
  19088. var d = 0.0; // tmp dot facet normal * facet position
  19089. var t0 = 0.0;
  19090. var projx = 0.0;
  19091. var projy = 0.0;
  19092. var projz = 0.0;
  19093. // Get all the facets in the same partitioning block than (x, y, z)
  19094. var facetPositions = this.getFacetLocalPositions();
  19095. var facetNormals = this.getFacetLocalNormals();
  19096. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  19097. if (!facetsInBlock) {
  19098. return null;
  19099. }
  19100. // Get the closest facet to (x, y, z)
  19101. var shortest = Number.MAX_VALUE; // init distance vars
  19102. var tmpDistance = shortest;
  19103. var fib; // current facet in the block
  19104. var norm; // current facet normal
  19105. var p0; // current facet barycenter position
  19106. // loop on all the facets in the current partitioning block
  19107. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  19108. fib = facetsInBlock[idx];
  19109. norm = facetNormals[fib];
  19110. p0 = facetPositions[fib];
  19111. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  19112. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  19113. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  19114. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  19115. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  19116. projx = x + norm.x * t0;
  19117. projy = y + norm.y * t0;
  19118. projz = z + norm.z * t0;
  19119. tmpx = projx - x;
  19120. tmpy = projy - y;
  19121. tmpz = projz - z;
  19122. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  19123. if (tmpDistance < shortest) {
  19124. shortest = tmpDistance;
  19125. closest = fib;
  19126. if (projected) {
  19127. projected.x = projx;
  19128. projected.y = projy;
  19129. projected.z = projz;
  19130. }
  19131. }
  19132. }
  19133. }
  19134. return closest;
  19135. };
  19136. /**
  19137. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  19138. */
  19139. AbstractMesh.prototype.getFacetDataParameters = function () {
  19140. return this._facetParameters;
  19141. };
  19142. /**
  19143. * Disables the feature FacetData and frees the related memory.
  19144. * Returns the AbstractMesh.
  19145. */
  19146. AbstractMesh.prototype.disableFacetData = function () {
  19147. if (this._facetDataEnabled) {
  19148. this._facetDataEnabled = false;
  19149. this._facetPositions = new Array();
  19150. this._facetNormals = new Array();
  19151. this._facetPartitioning = new Array();
  19152. this._facetParameters = null;
  19153. this._depthSortedIndices = new Uint32Array(0);
  19154. }
  19155. return this;
  19156. };
  19157. /**
  19158. * Updates the AbstractMesh indices array. Actually, used by the Mesh object.
  19159. * Returns the mesh.
  19160. */
  19161. AbstractMesh.prototype.updateIndices = function (indices) {
  19162. return this;
  19163. };
  19164. /**
  19165. * The mesh Geometry. Actually used by the Mesh object.
  19166. * Returns a blank geometry object.
  19167. */
  19168. /**
  19169. * Creates new normals data for the mesh.
  19170. * @param updatable.
  19171. */
  19172. AbstractMesh.prototype.createNormals = function (updatable) {
  19173. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19174. var indices = this.getIndices();
  19175. var normals;
  19176. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  19177. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19178. }
  19179. else {
  19180. normals = [];
  19181. }
  19182. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  19183. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  19184. };
  19185. /**
  19186. * Align the mesh with a normal.
  19187. * Returns the mesh.
  19188. */
  19189. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  19190. if (!upDirection) {
  19191. upDirection = BABYLON.Axis.Y;
  19192. }
  19193. var axisX = BABYLON.Tmp.Vector3[0];
  19194. var axisZ = BABYLON.Tmp.Vector3[1];
  19195. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  19196. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  19197. if (this.rotationQuaternion) {
  19198. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  19199. }
  19200. else {
  19201. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  19202. }
  19203. return this;
  19204. };
  19205. AbstractMesh.prototype.checkOcclusionQuery = function () {
  19206. var engine = this.getEngine();
  19207. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  19208. this._isOccluded = false;
  19209. return;
  19210. }
  19211. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  19212. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  19213. if (isOcclusionQueryAvailable) {
  19214. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  19215. this._isOcclusionQueryInProgress = false;
  19216. this._occlusionInternalRetryCounter = 0;
  19217. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  19218. }
  19219. else {
  19220. this._occlusionInternalRetryCounter++;
  19221. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  19222. this._isOcclusionQueryInProgress = false;
  19223. this._occlusionInternalRetryCounter = 0;
  19224. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  19225. // if strict continue the last state of the object.
  19226. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  19227. }
  19228. else {
  19229. return;
  19230. }
  19231. }
  19232. }
  19233. var scene = this.getScene();
  19234. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  19235. if (!this._occlusionQuery) {
  19236. this._occlusionQuery = engine.createQuery();
  19237. }
  19238. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  19239. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  19240. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  19241. this._isOcclusionQueryInProgress = true;
  19242. };
  19243. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  19244. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  19245. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  19246. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  19247. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  19248. return AbstractMesh;
  19249. }(BABYLON.TransformNode));
  19250. BABYLON.AbstractMesh = AbstractMesh;
  19251. })(BABYLON || (BABYLON = {}));
  19252. //# sourceMappingURL=babylon.abstractMesh.js.map
  19253. "use strict";
  19254. var BABYLON;
  19255. (function (BABYLON) {
  19256. /**
  19257. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  19258. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  19259. * 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.
  19260. */
  19261. var Light = /** @class */ (function (_super) {
  19262. __extends(Light, _super);
  19263. /**
  19264. * Creates a Light object in the scene.
  19265. * Documentation : http://doc.babylonjs.com/tutorials/lights
  19266. * @param name The firendly name of the light
  19267. * @param scene The scene the light belongs too
  19268. */
  19269. function Light(name, scene) {
  19270. var _this = _super.call(this, name, scene) || this;
  19271. /**
  19272. * Diffuse gives the basic color to an object.
  19273. */
  19274. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  19275. /**
  19276. * Specular produces a highlight color on an object.
  19277. * Note: This is note affecting PBR materials.
  19278. */
  19279. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  19280. /**
  19281. * Strength of the light.
  19282. * Note: By default it is define in the framework own unit.
  19283. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  19284. */
  19285. _this.intensity = 1.0;
  19286. /**
  19287. * Defines how far from the source the light is impacting in scene units.
  19288. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  19289. */
  19290. _this.range = Number.MAX_VALUE;
  19291. /**
  19292. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  19293. * of light.
  19294. */
  19295. _this._photometricScale = 1.0;
  19296. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  19297. _this._radius = 0.00001;
  19298. /**
  19299. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  19300. * exceeding the number allowed of the materials.
  19301. */
  19302. _this.renderPriority = 0;
  19303. /**
  19304. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  19305. * the current shadow generator.
  19306. */
  19307. _this.shadowEnabled = true;
  19308. _this._excludeWithLayerMask = 0;
  19309. _this._includeOnlyWithLayerMask = 0;
  19310. _this._lightmapMode = 0;
  19311. /**
  19312. * @ignore Internal use only.
  19313. */
  19314. _this._excludedMeshesIds = new Array();
  19315. /**
  19316. * @ignore Internal use only.
  19317. */
  19318. _this._includedOnlyMeshesIds = new Array();
  19319. _this.getScene().addLight(_this);
  19320. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  19321. _this._buildUniformLayout();
  19322. _this.includedOnlyMeshes = new Array();
  19323. _this.excludedMeshes = new Array();
  19324. _this._resyncMeshes();
  19325. return _this;
  19326. }
  19327. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  19328. /**
  19329. * If every light affecting the material is in this lightmapMode,
  19330. * material.lightmapTexture adds or multiplies
  19331. * (depends on material.useLightmapAsShadowmap)
  19332. * after every other light calculations.
  19333. */
  19334. get: function () {
  19335. return Light._LIGHTMAP_DEFAULT;
  19336. },
  19337. enumerable: true,
  19338. configurable: true
  19339. });
  19340. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  19341. /**
  19342. * material.lightmapTexture as only diffuse lighting from this light
  19343. * adds only specular lighting from this light
  19344. * adds dynamic shadows
  19345. */
  19346. get: function () {
  19347. return Light._LIGHTMAP_SPECULAR;
  19348. },
  19349. enumerable: true,
  19350. configurable: true
  19351. });
  19352. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  19353. /**
  19354. * material.lightmapTexture as only lighting
  19355. * no light calculation from this light
  19356. * only adds dynamic shadows from this light
  19357. */
  19358. get: function () {
  19359. return Light._LIGHTMAP_SHADOWSONLY;
  19360. },
  19361. enumerable: true,
  19362. configurable: true
  19363. });
  19364. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  19365. /**
  19366. * Each light type uses the default quantity according to its type:
  19367. * point/spot lights use luminous intensity
  19368. * directional lights use illuminance
  19369. */
  19370. get: function () {
  19371. return Light._INTENSITYMODE_AUTOMATIC;
  19372. },
  19373. enumerable: true,
  19374. configurable: true
  19375. });
  19376. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  19377. /**
  19378. * lumen (lm)
  19379. */
  19380. get: function () {
  19381. return Light._INTENSITYMODE_LUMINOUSPOWER;
  19382. },
  19383. enumerable: true,
  19384. configurable: true
  19385. });
  19386. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  19387. /**
  19388. * candela (lm/sr)
  19389. */
  19390. get: function () {
  19391. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  19392. },
  19393. enumerable: true,
  19394. configurable: true
  19395. });
  19396. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  19397. /**
  19398. * lux (lm/m^2)
  19399. */
  19400. get: function () {
  19401. return Light._INTENSITYMODE_ILLUMINANCE;
  19402. },
  19403. enumerable: true,
  19404. configurable: true
  19405. });
  19406. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  19407. /**
  19408. * nit (cd/m^2)
  19409. */
  19410. get: function () {
  19411. return Light._INTENSITYMODE_LUMINANCE;
  19412. },
  19413. enumerable: true,
  19414. configurable: true
  19415. });
  19416. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  19417. /**
  19418. * Light type const id of the point light.
  19419. */
  19420. get: function () {
  19421. return Light._LIGHTTYPEID_POINTLIGHT;
  19422. },
  19423. enumerable: true,
  19424. configurable: true
  19425. });
  19426. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  19427. /**
  19428. * Light type const id of the directional light.
  19429. */
  19430. get: function () {
  19431. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  19432. },
  19433. enumerable: true,
  19434. configurable: true
  19435. });
  19436. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  19437. /**
  19438. * Light type const id of the spot light.
  19439. */
  19440. get: function () {
  19441. return Light._LIGHTTYPEID_SPOTLIGHT;
  19442. },
  19443. enumerable: true,
  19444. configurable: true
  19445. });
  19446. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  19447. /**
  19448. * Light type const id of the hemispheric light.
  19449. */
  19450. get: function () {
  19451. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  19452. },
  19453. enumerable: true,
  19454. configurable: true
  19455. });
  19456. Object.defineProperty(Light.prototype, "intensityMode", {
  19457. /**
  19458. * Gets the photometric scale used to interpret the intensity.
  19459. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19460. */
  19461. get: function () {
  19462. return this._intensityMode;
  19463. },
  19464. /**
  19465. * Sets the photometric scale used to interpret the intensity.
  19466. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  19467. */
  19468. set: function (value) {
  19469. this._intensityMode = value;
  19470. this._computePhotometricScale();
  19471. },
  19472. enumerable: true,
  19473. configurable: true
  19474. });
  19475. ;
  19476. ;
  19477. Object.defineProperty(Light.prototype, "radius", {
  19478. /**
  19479. * Gets the light radius used by PBR Materials to simulate soft area lights.
  19480. */
  19481. get: function () {
  19482. return this._radius;
  19483. },
  19484. /**
  19485. * sets the light radius used by PBR Materials to simulate soft area lights.
  19486. */
  19487. set: function (value) {
  19488. this._radius = value;
  19489. this._computePhotometricScale();
  19490. },
  19491. enumerable: true,
  19492. configurable: true
  19493. });
  19494. ;
  19495. ;
  19496. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  19497. /**
  19498. * Gets the only meshes impacted by this light.
  19499. */
  19500. get: function () {
  19501. return this._includedOnlyMeshes;
  19502. },
  19503. /**
  19504. * Sets the only meshes impacted by this light.
  19505. */
  19506. set: function (value) {
  19507. this._includedOnlyMeshes = value;
  19508. this._hookArrayForIncludedOnly(value);
  19509. },
  19510. enumerable: true,
  19511. configurable: true
  19512. });
  19513. Object.defineProperty(Light.prototype, "excludedMeshes", {
  19514. /**
  19515. * Gets the meshes not impacted by this light.
  19516. */
  19517. get: function () {
  19518. return this._excludedMeshes;
  19519. },
  19520. /**
  19521. * Sets the meshes not impacted by this light.
  19522. */
  19523. set: function (value) {
  19524. this._excludedMeshes = value;
  19525. this._hookArrayForExcluded(value);
  19526. },
  19527. enumerable: true,
  19528. configurable: true
  19529. });
  19530. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  19531. /**
  19532. * Gets the layer id use to find what meshes are not impacted by the light.
  19533. * Inactive if 0
  19534. */
  19535. get: function () {
  19536. return this._excludeWithLayerMask;
  19537. },
  19538. /**
  19539. * Sets the layer id use to find what meshes are not impacted by the light.
  19540. * Inactive if 0
  19541. */
  19542. set: function (value) {
  19543. this._excludeWithLayerMask = value;
  19544. this._resyncMeshes();
  19545. },
  19546. enumerable: true,
  19547. configurable: true
  19548. });
  19549. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  19550. /**
  19551. * Gets the layer id use to find what meshes are impacted by the light.
  19552. * Inactive if 0
  19553. */
  19554. get: function () {
  19555. return this._includeOnlyWithLayerMask;
  19556. },
  19557. /**
  19558. * Sets the layer id use to find what meshes are impacted by the light.
  19559. * Inactive if 0
  19560. */
  19561. set: function (value) {
  19562. this._includeOnlyWithLayerMask = value;
  19563. this._resyncMeshes();
  19564. },
  19565. enumerable: true,
  19566. configurable: true
  19567. });
  19568. Object.defineProperty(Light.prototype, "lightmapMode", {
  19569. /**
  19570. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19571. */
  19572. get: function () {
  19573. return this._lightmapMode;
  19574. },
  19575. /**
  19576. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  19577. */
  19578. set: function (value) {
  19579. if (this._lightmapMode === value) {
  19580. return;
  19581. }
  19582. this._lightmapMode = value;
  19583. this._markMeshesAsLightDirty();
  19584. },
  19585. enumerable: true,
  19586. configurable: true
  19587. });
  19588. /**
  19589. * Returns the string "Light".
  19590. * @returns the class name
  19591. */
  19592. Light.prototype.getClassName = function () {
  19593. return "Light";
  19594. };
  19595. /**
  19596. * Converts the light information to a readable string for debug purpose.
  19597. * @param fullDetails Supports for multiple levels of logging within scene loading
  19598. * @returns the human readable light info
  19599. */
  19600. Light.prototype.toString = function (fullDetails) {
  19601. var ret = "Name: " + this.name;
  19602. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  19603. if (this.animations) {
  19604. for (var i = 0; i < this.animations.length; i++) {
  19605. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19606. }
  19607. }
  19608. if (fullDetails) {
  19609. }
  19610. return ret;
  19611. };
  19612. /**
  19613. * Set the enabled state of this node.
  19614. * @param value - the new enabled state
  19615. * @see isEnabled
  19616. */
  19617. Light.prototype.setEnabled = function (value) {
  19618. _super.prototype.setEnabled.call(this, value);
  19619. this._resyncMeshes();
  19620. };
  19621. /**
  19622. * Returns the Light associated shadow generator if any.
  19623. * @return the associated shadow generator.
  19624. */
  19625. Light.prototype.getShadowGenerator = function () {
  19626. return this._shadowGenerator;
  19627. };
  19628. /**
  19629. * Returns a Vector3, the absolute light position in the World.
  19630. * @returns the world space position of the light
  19631. */
  19632. Light.prototype.getAbsolutePosition = function () {
  19633. return BABYLON.Vector3.Zero();
  19634. };
  19635. /**
  19636. * Specifies if the light will affect the passed mesh.
  19637. * @param mesh The mesh to test against the light
  19638. * @return true the mesh is affected otherwise, false.
  19639. */
  19640. Light.prototype.canAffectMesh = function (mesh) {
  19641. if (!mesh) {
  19642. return true;
  19643. }
  19644. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  19645. return false;
  19646. }
  19647. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  19648. return false;
  19649. }
  19650. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  19651. return false;
  19652. }
  19653. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  19654. return false;
  19655. }
  19656. return true;
  19657. };
  19658. /**
  19659. * Computes and Returns the light World matrix.
  19660. * @returns the world matrix
  19661. */
  19662. Light.prototype.getWorldMatrix = function () {
  19663. this._currentRenderId = this.getScene().getRenderId();
  19664. var worldMatrix = this._getWorldMatrix();
  19665. if (this.parent && this.parent.getWorldMatrix) {
  19666. if (!this._parentedWorldMatrix) {
  19667. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  19668. }
  19669. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  19670. this._markSyncedWithParent();
  19671. return this._parentedWorldMatrix;
  19672. }
  19673. return worldMatrix;
  19674. };
  19675. /**
  19676. * Sort function to order lights for rendering.
  19677. * @param a First Light object to compare to second.
  19678. * @param b Second Light object to compare first.
  19679. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  19680. */
  19681. Light.CompareLightsPriority = function (a, b) {
  19682. //shadow-casting lights have priority over non-shadow-casting lights
  19683. //the renderPrioirty is a secondary sort criterion
  19684. if (a.shadowEnabled !== b.shadowEnabled) {
  19685. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  19686. }
  19687. return b.renderPriority - a.renderPriority;
  19688. };
  19689. /**
  19690. * Releases resources associated with this node.
  19691. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19692. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19693. */
  19694. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19695. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19696. if (this._shadowGenerator) {
  19697. this._shadowGenerator.dispose();
  19698. this._shadowGenerator = null;
  19699. }
  19700. // Animations
  19701. this.getScene().stopAnimation(this);
  19702. // Remove from meshes
  19703. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19704. var mesh = _a[_i];
  19705. mesh._removeLightSource(this);
  19706. }
  19707. this._uniformBuffer.dispose();
  19708. // Remove from scene
  19709. this.getScene().removeLight(this);
  19710. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19711. };
  19712. /**
  19713. * Returns the light type ID (integer).
  19714. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  19715. */
  19716. Light.prototype.getTypeID = function () {
  19717. return 0;
  19718. };
  19719. /**
  19720. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  19721. * @returns the scaled intensity in intensity mode unit
  19722. */
  19723. Light.prototype.getScaledIntensity = function () {
  19724. return this._photometricScale * this.intensity;
  19725. };
  19726. /**
  19727. * Returns a new Light object, named "name", from the current one.
  19728. * @param name The name of the cloned light
  19729. * @returns the new created light
  19730. */
  19731. Light.prototype.clone = function (name) {
  19732. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  19733. if (!constructor) {
  19734. return null;
  19735. }
  19736. return BABYLON.SerializationHelper.Clone(constructor, this);
  19737. };
  19738. /**
  19739. * Serializes the current light into a Serialization object.
  19740. * @returns the serialized object.
  19741. */
  19742. Light.prototype.serialize = function () {
  19743. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  19744. // Type
  19745. serializationObject.type = this.getTypeID();
  19746. // Parent
  19747. if (this.parent) {
  19748. serializationObject.parentId = this.parent.id;
  19749. }
  19750. // Inclusion / exclusions
  19751. if (this.excludedMeshes.length > 0) {
  19752. serializationObject.excludedMeshesIds = [];
  19753. this.excludedMeshes.forEach(function (mesh) {
  19754. serializationObject.excludedMeshesIds.push(mesh.id);
  19755. });
  19756. }
  19757. if (this.includedOnlyMeshes.length > 0) {
  19758. serializationObject.includedOnlyMeshesIds = [];
  19759. this.includedOnlyMeshes.forEach(function (mesh) {
  19760. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  19761. });
  19762. }
  19763. // Animations
  19764. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  19765. serializationObject.ranges = this.serializeAnimationRanges();
  19766. return serializationObject;
  19767. };
  19768. /**
  19769. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  19770. * This new light is named "name" and added to the passed scene.
  19771. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  19772. * @param name The friendly name of the light
  19773. * @param scene The scene the new light will belong to
  19774. * @returns the constructor function
  19775. */
  19776. Light.GetConstructorFromName = function (type, name, scene) {
  19777. switch (type) {
  19778. case 0:
  19779. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  19780. case 1:
  19781. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  19782. case 2:
  19783. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  19784. case 3:
  19785. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  19786. }
  19787. return null;
  19788. };
  19789. /**
  19790. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  19791. * @param parsedLight The JSON representation of the light
  19792. * @param scene The scene to create the parsed light in
  19793. * @returns the created light after parsing
  19794. */
  19795. Light.Parse = function (parsedLight, scene) {
  19796. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  19797. if (!constructor) {
  19798. return null;
  19799. }
  19800. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  19801. // Inclusion / exclusions
  19802. if (parsedLight.excludedMeshesIds) {
  19803. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  19804. }
  19805. if (parsedLight.includedOnlyMeshesIds) {
  19806. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  19807. }
  19808. // Parent
  19809. if (parsedLight.parentId) {
  19810. light._waitingParentId = parsedLight.parentId;
  19811. }
  19812. // Animations
  19813. if (parsedLight.animations) {
  19814. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  19815. var parsedAnimation = parsedLight.animations[animationIndex];
  19816. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  19817. }
  19818. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  19819. }
  19820. if (parsedLight.autoAnimate) {
  19821. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  19822. }
  19823. return light;
  19824. };
  19825. Light.prototype._hookArrayForExcluded = function (array) {
  19826. var _this = this;
  19827. var oldPush = array.push;
  19828. array.push = function () {
  19829. var items = [];
  19830. for (var _i = 0; _i < arguments.length; _i++) {
  19831. items[_i] = arguments[_i];
  19832. }
  19833. var result = oldPush.apply(array, items);
  19834. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  19835. var item = items_1[_a];
  19836. item._resyncLighSource(_this);
  19837. }
  19838. return result;
  19839. };
  19840. var oldSplice = array.splice;
  19841. array.splice = function (index, deleteCount) {
  19842. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19843. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  19844. var item = deleted_1[_i];
  19845. item._resyncLighSource(_this);
  19846. }
  19847. return deleted;
  19848. };
  19849. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  19850. var item = array_1[_i];
  19851. item._resyncLighSource(this);
  19852. }
  19853. };
  19854. Light.prototype._hookArrayForIncludedOnly = function (array) {
  19855. var _this = this;
  19856. var oldPush = array.push;
  19857. array.push = function () {
  19858. var items = [];
  19859. for (var _i = 0; _i < arguments.length; _i++) {
  19860. items[_i] = arguments[_i];
  19861. }
  19862. var result = oldPush.apply(array, items);
  19863. _this._resyncMeshes();
  19864. return result;
  19865. };
  19866. var oldSplice = array.splice;
  19867. array.splice = function (index, deleteCount) {
  19868. var deleted = oldSplice.apply(array, [index, deleteCount]);
  19869. _this._resyncMeshes();
  19870. return deleted;
  19871. };
  19872. this._resyncMeshes();
  19873. };
  19874. Light.prototype._resyncMeshes = function () {
  19875. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19876. var mesh = _a[_i];
  19877. mesh._resyncLighSource(this);
  19878. }
  19879. };
  19880. /**
  19881. * Forces the meshes to update their light related information in their rendering used effects
  19882. * @ignore Internal Use Only
  19883. */
  19884. Light.prototype._markMeshesAsLightDirty = function () {
  19885. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  19886. var mesh = _a[_i];
  19887. if (mesh._lightSources.indexOf(this) !== -1) {
  19888. mesh._markSubMeshesAsLightDirty();
  19889. }
  19890. }
  19891. };
  19892. /**
  19893. * Recomputes the cached photometric scale if needed.
  19894. */
  19895. Light.prototype._computePhotometricScale = function () {
  19896. this._photometricScale = this._getPhotometricScale();
  19897. this.getScene().resetCachedMaterial();
  19898. };
  19899. /**
  19900. * Returns the Photometric Scale according to the light type and intensity mode.
  19901. */
  19902. Light.prototype._getPhotometricScale = function () {
  19903. var photometricScale = 0.0;
  19904. var lightTypeID = this.getTypeID();
  19905. //get photometric mode
  19906. var photometricMode = this.intensityMode;
  19907. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  19908. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  19909. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  19910. }
  19911. else {
  19912. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  19913. }
  19914. }
  19915. //compute photometric scale
  19916. switch (lightTypeID) {
  19917. case Light.LIGHTTYPEID_POINTLIGHT:
  19918. case Light.LIGHTTYPEID_SPOTLIGHT:
  19919. switch (photometricMode) {
  19920. case Light.INTENSITYMODE_LUMINOUSPOWER:
  19921. photometricScale = 1.0 / (4.0 * Math.PI);
  19922. break;
  19923. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  19924. photometricScale = 1.0;
  19925. break;
  19926. case Light.INTENSITYMODE_LUMINANCE:
  19927. photometricScale = this.radius * this.radius;
  19928. break;
  19929. }
  19930. break;
  19931. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  19932. switch (photometricMode) {
  19933. case Light.INTENSITYMODE_ILLUMINANCE:
  19934. photometricScale = 1.0;
  19935. break;
  19936. case Light.INTENSITYMODE_LUMINANCE:
  19937. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  19938. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  19939. var apexAngleRadians = this.radius;
  19940. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  19941. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  19942. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  19943. photometricScale = solidAngle;
  19944. break;
  19945. }
  19946. break;
  19947. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  19948. // No fall off in hemisperic light.
  19949. photometricScale = 1.0;
  19950. break;
  19951. }
  19952. return photometricScale;
  19953. };
  19954. /**
  19955. * Reorder the light in the scene according to their defined priority.
  19956. * @ignore Internal Use Only
  19957. */
  19958. Light.prototype._reorderLightsInScene = function () {
  19959. var scene = this.getScene();
  19960. if (this._renderPriority != 0) {
  19961. scene.requireLightSorting = true;
  19962. }
  19963. this.getScene().sortLightsByPriority();
  19964. };
  19965. //lightmapMode Consts
  19966. Light._LIGHTMAP_DEFAULT = 0;
  19967. Light._LIGHTMAP_SPECULAR = 1;
  19968. Light._LIGHTMAP_SHADOWSONLY = 2;
  19969. // Intensity Mode Consts
  19970. Light._INTENSITYMODE_AUTOMATIC = 0;
  19971. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  19972. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  19973. Light._INTENSITYMODE_ILLUMINANCE = 3;
  19974. Light._INTENSITYMODE_LUMINANCE = 4;
  19975. // Light types ids const.
  19976. Light._LIGHTTYPEID_POINTLIGHT = 0;
  19977. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  19978. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  19979. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  19980. __decorate([
  19981. BABYLON.serializeAsColor3()
  19982. ], Light.prototype, "diffuse", void 0);
  19983. __decorate([
  19984. BABYLON.serializeAsColor3()
  19985. ], Light.prototype, "specular", void 0);
  19986. __decorate([
  19987. BABYLON.serialize()
  19988. ], Light.prototype, "intensity", void 0);
  19989. __decorate([
  19990. BABYLON.serialize()
  19991. ], Light.prototype, "range", void 0);
  19992. __decorate([
  19993. BABYLON.serialize()
  19994. ], Light.prototype, "intensityMode", null);
  19995. __decorate([
  19996. BABYLON.serialize()
  19997. ], Light.prototype, "radius", null);
  19998. __decorate([
  19999. BABYLON.serialize()
  20000. ], Light.prototype, "_renderPriority", void 0);
  20001. __decorate([
  20002. BABYLON.expandToProperty("_reorderLightsInScene")
  20003. ], Light.prototype, "renderPriority", void 0);
  20004. __decorate([
  20005. BABYLON.serialize()
  20006. ], Light.prototype, "shadowEnabled", void 0);
  20007. __decorate([
  20008. BABYLON.serialize("excludeWithLayerMask")
  20009. ], Light.prototype, "_excludeWithLayerMask", void 0);
  20010. __decorate([
  20011. BABYLON.serialize("includeOnlyWithLayerMask")
  20012. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  20013. __decorate([
  20014. BABYLON.serialize("lightmapMode")
  20015. ], Light.prototype, "_lightmapMode", void 0);
  20016. return Light;
  20017. }(BABYLON.Node));
  20018. BABYLON.Light = Light;
  20019. })(BABYLON || (BABYLON = {}));
  20020. //# sourceMappingURL=babylon.light.js.map
  20021. "use strict";
  20022. var BABYLON;
  20023. (function (BABYLON) {
  20024. var Camera = /** @class */ (function (_super) {
  20025. __extends(Camera, _super);
  20026. function Camera(name, position, scene) {
  20027. var _this = _super.call(this, name, scene) || this;
  20028. /**
  20029. * The vector the camera should consider as up.
  20030. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  20031. */
  20032. _this.upVector = BABYLON.Vector3.Up();
  20033. _this.orthoLeft = null;
  20034. _this.orthoRight = null;
  20035. _this.orthoBottom = null;
  20036. _this.orthoTop = null;
  20037. /**
  20038. * FOV is set in Radians. (default is 0.8)
  20039. */
  20040. _this.fov = 0.8;
  20041. _this.minZ = 1;
  20042. _this.maxZ = 10000.0;
  20043. _this.inertia = 0.9;
  20044. _this.mode = Camera.PERSPECTIVE_CAMERA;
  20045. _this.isIntermediate = false;
  20046. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  20047. /**
  20048. * Restricts the camera to viewing objects with the same layerMask.
  20049. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  20050. */
  20051. _this.layerMask = 0x0FFFFFFF;
  20052. /**
  20053. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  20054. */
  20055. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  20056. // Camera rig members
  20057. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  20058. _this._rigCameras = new Array();
  20059. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  20060. _this._skipRendering = false;
  20061. _this.customRenderTargets = new Array();
  20062. // Observables
  20063. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  20064. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  20065. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  20066. _this.onRestoreStateObservable = new BABYLON.Observable();
  20067. // Cache
  20068. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  20069. _this._projectionMatrix = new BABYLON.Matrix();
  20070. _this._doNotComputeProjectionMatrix = false;
  20071. _this._postProcesses = new Array();
  20072. _this._transformMatrix = BABYLON.Matrix.Zero();
  20073. _this._activeMeshes = new BABYLON.SmartArray(256);
  20074. _this._globalPosition = BABYLON.Vector3.Zero();
  20075. _this._refreshFrustumPlanes = true;
  20076. _this.getScene().addCamera(_this);
  20077. if (!_this.getScene().activeCamera) {
  20078. _this.getScene().activeCamera = _this;
  20079. }
  20080. _this.position = position;
  20081. return _this;
  20082. }
  20083. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  20084. get: function () {
  20085. return Camera._PERSPECTIVE_CAMERA;
  20086. },
  20087. enumerable: true,
  20088. configurable: true
  20089. });
  20090. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  20091. get: function () {
  20092. return Camera._ORTHOGRAPHIC_CAMERA;
  20093. },
  20094. enumerable: true,
  20095. configurable: true
  20096. });
  20097. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  20098. /**
  20099. * This is the default FOV mode for perspective cameras.
  20100. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  20101. *
  20102. */
  20103. get: function () {
  20104. return Camera._FOVMODE_VERTICAL_FIXED;
  20105. },
  20106. enumerable: true,
  20107. configurable: true
  20108. });
  20109. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  20110. /**
  20111. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  20112. *
  20113. */
  20114. get: function () {
  20115. return Camera._FOVMODE_HORIZONTAL_FIXED;
  20116. },
  20117. enumerable: true,
  20118. configurable: true
  20119. });
  20120. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  20121. get: function () {
  20122. return Camera._RIG_MODE_NONE;
  20123. },
  20124. enumerable: true,
  20125. configurable: true
  20126. });
  20127. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  20128. get: function () {
  20129. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  20130. },
  20131. enumerable: true,
  20132. configurable: true
  20133. });
  20134. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  20135. get: function () {
  20136. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  20137. },
  20138. enumerable: true,
  20139. configurable: true
  20140. });
  20141. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  20142. get: function () {
  20143. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20144. },
  20145. enumerable: true,
  20146. configurable: true
  20147. });
  20148. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  20149. get: function () {
  20150. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  20151. },
  20152. enumerable: true,
  20153. configurable: true
  20154. });
  20155. Object.defineProperty(Camera, "RIG_MODE_VR", {
  20156. get: function () {
  20157. return Camera._RIG_MODE_VR;
  20158. },
  20159. enumerable: true,
  20160. configurable: true
  20161. });
  20162. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  20163. get: function () {
  20164. return Camera._RIG_MODE_WEBVR;
  20165. },
  20166. enumerable: true,
  20167. configurable: true
  20168. });
  20169. /**
  20170. * Store current camera state (fov, position, etc..)
  20171. */
  20172. Camera.prototype.storeState = function () {
  20173. this._stateStored = true;
  20174. this._storedFov = this.fov;
  20175. return this;
  20176. };
  20177. /**
  20178. * Restores the camera state values if it has been stored. You must call storeState() first
  20179. */
  20180. Camera.prototype._restoreStateValues = function () {
  20181. if (!this._stateStored) {
  20182. return false;
  20183. }
  20184. this.fov = this._storedFov;
  20185. return true;
  20186. };
  20187. /**
  20188. * Restored camera state. You must call storeState() first
  20189. */
  20190. Camera.prototype.restoreState = function () {
  20191. if (this._restoreStateValues()) {
  20192. this.onRestoreStateObservable.notifyObservers(this);
  20193. return true;
  20194. }
  20195. return false;
  20196. };
  20197. Camera.prototype.getClassName = function () {
  20198. return "Camera";
  20199. };
  20200. /**
  20201. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  20202. */
  20203. Camera.prototype.toString = function (fullDetails) {
  20204. var ret = "Name: " + this.name;
  20205. ret += ", type: " + this.getClassName();
  20206. if (this.animations) {
  20207. for (var i = 0; i < this.animations.length; i++) {
  20208. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  20209. }
  20210. }
  20211. if (fullDetails) {
  20212. }
  20213. return ret;
  20214. };
  20215. Object.defineProperty(Camera.prototype, "globalPosition", {
  20216. get: function () {
  20217. return this._globalPosition;
  20218. },
  20219. enumerable: true,
  20220. configurable: true
  20221. });
  20222. Camera.prototype.getActiveMeshes = function () {
  20223. return this._activeMeshes;
  20224. };
  20225. Camera.prototype.isActiveMesh = function (mesh) {
  20226. return (this._activeMeshes.indexOf(mesh) !== -1);
  20227. };
  20228. //Cache
  20229. Camera.prototype._initCache = function () {
  20230. _super.prototype._initCache.call(this);
  20231. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20232. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20233. this._cache.mode = undefined;
  20234. this._cache.minZ = undefined;
  20235. this._cache.maxZ = undefined;
  20236. this._cache.fov = undefined;
  20237. this._cache.fovMode = undefined;
  20238. this._cache.aspectRatio = undefined;
  20239. this._cache.orthoLeft = undefined;
  20240. this._cache.orthoRight = undefined;
  20241. this._cache.orthoBottom = undefined;
  20242. this._cache.orthoTop = undefined;
  20243. this._cache.renderWidth = undefined;
  20244. this._cache.renderHeight = undefined;
  20245. };
  20246. Camera.prototype._updateCache = function (ignoreParentClass) {
  20247. if (!ignoreParentClass) {
  20248. _super.prototype._updateCache.call(this);
  20249. }
  20250. this._cache.position.copyFrom(this.position);
  20251. this._cache.upVector.copyFrom(this.upVector);
  20252. };
  20253. // Synchronized
  20254. Camera.prototype._isSynchronized = function () {
  20255. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  20256. };
  20257. Camera.prototype._isSynchronizedViewMatrix = function () {
  20258. if (!_super.prototype._isSynchronized.call(this))
  20259. return false;
  20260. return this._cache.position.equals(this.position)
  20261. && this._cache.upVector.equals(this.upVector)
  20262. && this.isSynchronizedWithParent();
  20263. };
  20264. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  20265. var check = this._cache.mode === this.mode
  20266. && this._cache.minZ === this.minZ
  20267. && this._cache.maxZ === this.maxZ;
  20268. if (!check) {
  20269. return false;
  20270. }
  20271. var engine = this.getEngine();
  20272. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20273. check = this._cache.fov === this.fov
  20274. && this._cache.fovMode === this.fovMode
  20275. && this._cache.aspectRatio === engine.getAspectRatio(this);
  20276. }
  20277. else {
  20278. check = this._cache.orthoLeft === this.orthoLeft
  20279. && this._cache.orthoRight === this.orthoRight
  20280. && this._cache.orthoBottom === this.orthoBottom
  20281. && this._cache.orthoTop === this.orthoTop
  20282. && this._cache.renderWidth === engine.getRenderWidth()
  20283. && this._cache.renderHeight === engine.getRenderHeight();
  20284. }
  20285. return check;
  20286. };
  20287. // Controls
  20288. Camera.prototype.attachControl = function (element, noPreventDefault) {
  20289. };
  20290. Camera.prototype.detachControl = function (element) {
  20291. };
  20292. Camera.prototype.update = function () {
  20293. this._checkInputs();
  20294. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20295. this._updateRigCameras();
  20296. }
  20297. };
  20298. Camera.prototype._checkInputs = function () {
  20299. this.onAfterCheckInputsObservable.notifyObservers(this);
  20300. };
  20301. Object.defineProperty(Camera.prototype, "rigCameras", {
  20302. get: function () {
  20303. return this._rigCameras;
  20304. },
  20305. enumerable: true,
  20306. configurable: true
  20307. });
  20308. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  20309. get: function () {
  20310. return this._rigPostProcess;
  20311. },
  20312. enumerable: true,
  20313. configurable: true
  20314. });
  20315. /**
  20316. * Internal, gets the first post proces.
  20317. * @returns the first post process to be run on this camera.
  20318. */
  20319. Camera.prototype._getFirstPostProcess = function () {
  20320. for (var pp in this._postProcesses) {
  20321. if (this._postProcesses[pp] !== null) {
  20322. return this._postProcesses[pp];
  20323. }
  20324. }
  20325. return null;
  20326. };
  20327. Camera.prototype._cascadePostProcessesToRigCams = function () {
  20328. // invalidate framebuffer
  20329. var firstPostProcess = this._getFirstPostProcess();
  20330. if (firstPostProcess) {
  20331. firstPostProcess.markTextureDirty();
  20332. }
  20333. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  20334. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  20335. var cam = this._rigCameras[i];
  20336. var rigPostProcess = cam._rigPostProcess;
  20337. // for VR rig, there does not have to be a post process
  20338. if (rigPostProcess) {
  20339. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  20340. if (isPass) {
  20341. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  20342. cam.isIntermediate = this._postProcesses.length === 0;
  20343. }
  20344. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  20345. rigPostProcess.markTextureDirty();
  20346. }
  20347. else {
  20348. cam._postProcesses = this._postProcesses.slice(0);
  20349. }
  20350. }
  20351. };
  20352. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  20353. if (insertAt === void 0) { insertAt = null; }
  20354. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  20355. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  20356. return 0;
  20357. }
  20358. if (insertAt == null || insertAt < 0) {
  20359. this._postProcesses.push(postProcess);
  20360. }
  20361. else if (this._postProcesses[insertAt] === null) {
  20362. this._postProcesses[insertAt] = postProcess;
  20363. }
  20364. else {
  20365. this._postProcesses.splice(insertAt, 0, postProcess);
  20366. }
  20367. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20368. return this._postProcesses.indexOf(postProcess);
  20369. };
  20370. Camera.prototype.detachPostProcess = function (postProcess) {
  20371. var idx = this._postProcesses.indexOf(postProcess);
  20372. if (idx !== -1) {
  20373. this._postProcesses[idx] = null;
  20374. }
  20375. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  20376. };
  20377. Camera.prototype.getWorldMatrix = function () {
  20378. if (!this._worldMatrix) {
  20379. this._worldMatrix = BABYLON.Matrix.Identity();
  20380. }
  20381. var viewMatrix = this.getViewMatrix();
  20382. viewMatrix.invertToRef(this._worldMatrix);
  20383. return this._worldMatrix;
  20384. };
  20385. Camera.prototype._getViewMatrix = function () {
  20386. return BABYLON.Matrix.Identity();
  20387. };
  20388. Camera.prototype.getViewMatrix = function (force) {
  20389. if (!force && this._isSynchronizedViewMatrix()) {
  20390. return this._computedViewMatrix;
  20391. }
  20392. this.updateCache();
  20393. this._computedViewMatrix = this._getViewMatrix();
  20394. this._currentRenderId = this.getScene().getRenderId();
  20395. this._refreshFrustumPlanes = true;
  20396. if (!this.parent || !this.parent.getWorldMatrix) {
  20397. this._globalPosition.copyFrom(this.position);
  20398. }
  20399. else {
  20400. if (!this._worldMatrix) {
  20401. this._worldMatrix = BABYLON.Matrix.Identity();
  20402. }
  20403. this._computedViewMatrix.invertToRef(this._worldMatrix);
  20404. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  20405. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  20406. this._computedViewMatrix.invert();
  20407. this._markSyncedWithParent();
  20408. }
  20409. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  20410. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  20411. }
  20412. this.onViewMatrixChangedObservable.notifyObservers(this);
  20413. return this._computedViewMatrix;
  20414. };
  20415. Camera.prototype.freezeProjectionMatrix = function (projection) {
  20416. this._doNotComputeProjectionMatrix = true;
  20417. if (projection !== undefined) {
  20418. this._projectionMatrix = projection;
  20419. }
  20420. };
  20421. ;
  20422. Camera.prototype.unfreezeProjectionMatrix = function () {
  20423. this._doNotComputeProjectionMatrix = false;
  20424. };
  20425. ;
  20426. Camera.prototype.getProjectionMatrix = function (force) {
  20427. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  20428. return this._projectionMatrix;
  20429. }
  20430. // Cache
  20431. this._cache.mode = this.mode;
  20432. this._cache.minZ = this.minZ;
  20433. this._cache.maxZ = this.maxZ;
  20434. // Matrix
  20435. this._refreshFrustumPlanes = true;
  20436. var engine = this.getEngine();
  20437. var scene = this.getScene();
  20438. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  20439. this._cache.fov = this.fov;
  20440. this._cache.fovMode = this.fovMode;
  20441. this._cache.aspectRatio = engine.getAspectRatio(this);
  20442. if (this.minZ <= 0) {
  20443. this.minZ = 0.1;
  20444. }
  20445. if (scene.useRightHandedSystem) {
  20446. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20447. }
  20448. else {
  20449. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  20450. }
  20451. }
  20452. else {
  20453. var halfWidth = engine.getRenderWidth() / 2.0;
  20454. var halfHeight = engine.getRenderHeight() / 2.0;
  20455. if (scene.useRightHandedSystem) {
  20456. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20457. }
  20458. else {
  20459. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  20460. }
  20461. this._cache.orthoLeft = this.orthoLeft;
  20462. this._cache.orthoRight = this.orthoRight;
  20463. this._cache.orthoBottom = this.orthoBottom;
  20464. this._cache.orthoTop = this.orthoTop;
  20465. this._cache.renderWidth = engine.getRenderWidth();
  20466. this._cache.renderHeight = engine.getRenderHeight();
  20467. }
  20468. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  20469. return this._projectionMatrix;
  20470. };
  20471. Camera.prototype.getTranformationMatrix = function () {
  20472. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  20473. return this._transformMatrix;
  20474. };
  20475. Camera.prototype.updateFrustumPlanes = function () {
  20476. if (!this._refreshFrustumPlanes) {
  20477. return;
  20478. }
  20479. this.getTranformationMatrix();
  20480. if (!this._frustumPlanes) {
  20481. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  20482. }
  20483. else {
  20484. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  20485. }
  20486. this._refreshFrustumPlanes = false;
  20487. };
  20488. Camera.prototype.isInFrustum = function (target) {
  20489. this.updateFrustumPlanes();
  20490. return target.isInFrustum(this._frustumPlanes);
  20491. };
  20492. Camera.prototype.isCompletelyInFrustum = function (target) {
  20493. this.updateFrustumPlanes();
  20494. return target.isCompletelyInFrustum(this._frustumPlanes);
  20495. };
  20496. Camera.prototype.getForwardRay = function (length, transform, origin) {
  20497. if (length === void 0) { length = 100; }
  20498. if (!transform) {
  20499. transform = this.getWorldMatrix();
  20500. }
  20501. if (!origin) {
  20502. origin = this.position;
  20503. }
  20504. var forward = new BABYLON.Vector3(0, 0, 1);
  20505. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  20506. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  20507. return new BABYLON.Ray(origin, direction, length);
  20508. };
  20509. /**
  20510. * Releases resources associated with this node.
  20511. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20512. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20513. */
  20514. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20515. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20516. // Observables
  20517. this.onViewMatrixChangedObservable.clear();
  20518. this.onProjectionMatrixChangedObservable.clear();
  20519. this.onAfterCheckInputsObservable.clear();
  20520. this.onRestoreStateObservable.clear();
  20521. // Inputs
  20522. if (this.inputs) {
  20523. this.inputs.clear();
  20524. }
  20525. // Animations
  20526. this.getScene().stopAnimation(this);
  20527. // Remove from scene
  20528. this.getScene().removeCamera(this);
  20529. while (this._rigCameras.length > 0) {
  20530. var camera = this._rigCameras.pop();
  20531. if (camera) {
  20532. camera.dispose();
  20533. }
  20534. }
  20535. // Postprocesses
  20536. if (this._rigPostProcess) {
  20537. this._rigPostProcess.dispose(this);
  20538. this._rigPostProcess = null;
  20539. this._postProcesses = [];
  20540. }
  20541. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20542. this._rigPostProcess = null;
  20543. this._postProcesses = [];
  20544. }
  20545. else {
  20546. var i = this._postProcesses.length;
  20547. while (--i >= 0) {
  20548. var postProcess = this._postProcesses[i];
  20549. if (postProcess) {
  20550. postProcess.dispose(this);
  20551. }
  20552. }
  20553. }
  20554. // Render targets
  20555. var i = this.customRenderTargets.length;
  20556. while (--i >= 0) {
  20557. this.customRenderTargets[i].dispose();
  20558. }
  20559. this.customRenderTargets = [];
  20560. // Active Meshes
  20561. this._activeMeshes.dispose();
  20562. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20563. };
  20564. Object.defineProperty(Camera.prototype, "leftCamera", {
  20565. // ---- Camera rigs section ----
  20566. get: function () {
  20567. if (this._rigCameras.length < 1) {
  20568. return null;
  20569. }
  20570. return this._rigCameras[0];
  20571. },
  20572. enumerable: true,
  20573. configurable: true
  20574. });
  20575. Object.defineProperty(Camera.prototype, "rightCamera", {
  20576. get: function () {
  20577. if (this._rigCameras.length < 2) {
  20578. return null;
  20579. }
  20580. return this._rigCameras[1];
  20581. },
  20582. enumerable: true,
  20583. configurable: true
  20584. });
  20585. Camera.prototype.getLeftTarget = function () {
  20586. if (this._rigCameras.length < 1) {
  20587. return null;
  20588. }
  20589. return this._rigCameras[0].getTarget();
  20590. };
  20591. Camera.prototype.getRightTarget = function () {
  20592. if (this._rigCameras.length < 2) {
  20593. return null;
  20594. }
  20595. return this._rigCameras[1].getTarget();
  20596. };
  20597. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  20598. if (this.cameraRigMode === mode) {
  20599. return;
  20600. }
  20601. while (this._rigCameras.length > 0) {
  20602. var camera = this._rigCameras.pop();
  20603. if (camera) {
  20604. camera.dispose();
  20605. }
  20606. }
  20607. this.cameraRigMode = mode;
  20608. this._cameraRigParams = {};
  20609. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  20610. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  20611. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  20612. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  20613. // create the rig cameras, unless none
  20614. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  20615. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  20616. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  20617. if (leftCamera && rightCamera) {
  20618. this._rigCameras.push(leftCamera);
  20619. this._rigCameras.push(rightCamera);
  20620. }
  20621. }
  20622. switch (this.cameraRigMode) {
  20623. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  20624. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20625. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  20626. break;
  20627. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  20628. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  20629. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  20630. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  20631. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  20632. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  20633. break;
  20634. case Camera.RIG_MODE_VR:
  20635. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  20636. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  20637. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20638. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20639. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  20640. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  20641. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  20642. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  20643. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20644. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20645. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  20646. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  20647. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  20648. if (metrics.compensateDistortion) {
  20649. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  20650. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  20651. }
  20652. break;
  20653. case Camera.RIG_MODE_WEBVR:
  20654. if (rigParams.vrDisplay) {
  20655. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  20656. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  20657. //Left eye
  20658. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  20659. this._rigCameras[0].setCameraRigParameter("left", true);
  20660. //leaving this for future reference
  20661. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  20662. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  20663. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  20664. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20665. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20666. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20667. this._rigCameras[0].parent = this;
  20668. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  20669. //Right eye
  20670. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  20671. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  20672. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  20673. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  20674. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  20675. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  20676. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  20677. this._rigCameras[1].parent = this;
  20678. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  20679. if (Camera.UseAlternateWebVRRendering) {
  20680. this._rigCameras[1]._skipRendering = true;
  20681. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  20682. }
  20683. }
  20684. break;
  20685. }
  20686. this._cascadePostProcessesToRigCams();
  20687. this.update();
  20688. };
  20689. Camera.prototype._getVRProjectionMatrix = function () {
  20690. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  20691. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  20692. return this._projectionMatrix;
  20693. };
  20694. Camera.prototype._updateCameraRotationMatrix = function () {
  20695. //Here for WebVR
  20696. };
  20697. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  20698. //Here for WebVR
  20699. };
  20700. /**
  20701. * This function MUST be overwritten by the different WebVR cameras available.
  20702. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20703. */
  20704. Camera.prototype._getWebVRProjectionMatrix = function () {
  20705. return BABYLON.Matrix.Identity();
  20706. };
  20707. /**
  20708. * This function MUST be overwritten by the different WebVR cameras available.
  20709. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  20710. */
  20711. Camera.prototype._getWebVRViewMatrix = function () {
  20712. return BABYLON.Matrix.Identity();
  20713. };
  20714. Camera.prototype.setCameraRigParameter = function (name, value) {
  20715. if (!this._cameraRigParams) {
  20716. this._cameraRigParams = {};
  20717. }
  20718. this._cameraRigParams[name] = value;
  20719. //provisionnally:
  20720. if (name === "interaxialDistance") {
  20721. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  20722. }
  20723. };
  20724. /**
  20725. * needs to be overridden by children so sub has required properties to be copied
  20726. */
  20727. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  20728. return null;
  20729. };
  20730. /**
  20731. * May need to be overridden by children
  20732. */
  20733. Camera.prototype._updateRigCameras = function () {
  20734. for (var i = 0; i < this._rigCameras.length; i++) {
  20735. this._rigCameras[i].minZ = this.minZ;
  20736. this._rigCameras[i].maxZ = this.maxZ;
  20737. this._rigCameras[i].fov = this.fov;
  20738. }
  20739. // only update viewport when ANAGLYPH
  20740. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  20741. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  20742. }
  20743. };
  20744. Camera.prototype._setupInputs = function () {
  20745. };
  20746. Camera.prototype.serialize = function () {
  20747. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20748. // Type
  20749. serializationObject.type = this.getClassName();
  20750. // Parent
  20751. if (this.parent) {
  20752. serializationObject.parentId = this.parent.id;
  20753. }
  20754. if (this.inputs) {
  20755. this.inputs.serialize(serializationObject);
  20756. }
  20757. // Animations
  20758. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20759. serializationObject.ranges = this.serializeAnimationRanges();
  20760. return serializationObject;
  20761. };
  20762. Camera.prototype.clone = function (name) {
  20763. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  20764. };
  20765. Camera.prototype.getDirection = function (localAxis) {
  20766. var result = BABYLON.Vector3.Zero();
  20767. this.getDirectionToRef(localAxis, result);
  20768. return result;
  20769. };
  20770. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  20771. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  20772. };
  20773. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  20774. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  20775. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  20776. switch (type) {
  20777. case "ArcRotateCamera":
  20778. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  20779. case "DeviceOrientationCamera":
  20780. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  20781. case "FollowCamera":
  20782. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  20783. case "ArcFollowCamera":
  20784. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  20785. case "GamepadCamera":
  20786. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20787. case "TouchCamera":
  20788. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  20789. case "VirtualJoysticksCamera":
  20790. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  20791. case "WebVRFreeCamera":
  20792. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20793. case "WebVRGamepadCamera":
  20794. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20795. case "VRDeviceOrientationFreeCamera":
  20796. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  20797. case "VRDeviceOrientationGamepadCamera":
  20798. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  20799. case "AnaglyphArcRotateCamera":
  20800. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20801. case "AnaglyphFreeCamera":
  20802. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20803. case "AnaglyphGamepadCamera":
  20804. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20805. case "AnaglyphUniversalCamera":
  20806. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  20807. case "StereoscopicArcRotateCamera":
  20808. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20809. case "StereoscopicFreeCamera":
  20810. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20811. case "StereoscopicGamepadCamera":
  20812. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20813. case "StereoscopicUniversalCamera":
  20814. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  20815. case "FreeCamera":// Forcing Universal here
  20816. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20817. default:// Universal Camera is the default value
  20818. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  20819. }
  20820. };
  20821. Camera.prototype.computeWorldMatrix = function () {
  20822. return this.getWorldMatrix();
  20823. };
  20824. Camera.Parse = function (parsedCamera, scene) {
  20825. var type = parsedCamera.type;
  20826. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  20827. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  20828. // Parent
  20829. if (parsedCamera.parentId) {
  20830. camera._waitingParentId = parsedCamera.parentId;
  20831. }
  20832. //If camera has an input manager, let it parse inputs settings
  20833. if (camera.inputs) {
  20834. camera.inputs.parse(parsedCamera);
  20835. camera._setupInputs();
  20836. }
  20837. if (camera.setPosition) {
  20838. camera.position.copyFromFloats(0, 0, 0);
  20839. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  20840. }
  20841. // Target
  20842. if (parsedCamera.target) {
  20843. if (camera.setTarget) {
  20844. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  20845. }
  20846. }
  20847. // Apply 3d rig, when found
  20848. if (parsedCamera.cameraRigMode) {
  20849. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  20850. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  20851. }
  20852. // Animations
  20853. if (parsedCamera.animations) {
  20854. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  20855. var parsedAnimation = parsedCamera.animations[animationIndex];
  20856. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20857. }
  20858. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  20859. }
  20860. if (parsedCamera.autoAnimate) {
  20861. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  20862. }
  20863. return camera;
  20864. };
  20865. // Statics
  20866. Camera._PERSPECTIVE_CAMERA = 0;
  20867. Camera._ORTHOGRAPHIC_CAMERA = 1;
  20868. Camera._FOVMODE_VERTICAL_FIXED = 0;
  20869. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  20870. Camera._RIG_MODE_NONE = 0;
  20871. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  20872. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  20873. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  20874. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  20875. Camera._RIG_MODE_VR = 20;
  20876. Camera._RIG_MODE_WEBVR = 21;
  20877. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  20878. Camera.UseAlternateWebVRRendering = false;
  20879. __decorate([
  20880. BABYLON.serializeAsVector3()
  20881. ], Camera.prototype, "position", void 0);
  20882. __decorate([
  20883. BABYLON.serializeAsVector3()
  20884. ], Camera.prototype, "upVector", void 0);
  20885. __decorate([
  20886. BABYLON.serialize()
  20887. ], Camera.prototype, "orthoLeft", void 0);
  20888. __decorate([
  20889. BABYLON.serialize()
  20890. ], Camera.prototype, "orthoRight", void 0);
  20891. __decorate([
  20892. BABYLON.serialize()
  20893. ], Camera.prototype, "orthoBottom", void 0);
  20894. __decorate([
  20895. BABYLON.serialize()
  20896. ], Camera.prototype, "orthoTop", void 0);
  20897. __decorate([
  20898. BABYLON.serialize()
  20899. ], Camera.prototype, "fov", void 0);
  20900. __decorate([
  20901. BABYLON.serialize()
  20902. ], Camera.prototype, "minZ", void 0);
  20903. __decorate([
  20904. BABYLON.serialize()
  20905. ], Camera.prototype, "maxZ", void 0);
  20906. __decorate([
  20907. BABYLON.serialize()
  20908. ], Camera.prototype, "inertia", void 0);
  20909. __decorate([
  20910. BABYLON.serialize()
  20911. ], Camera.prototype, "mode", void 0);
  20912. __decorate([
  20913. BABYLON.serialize()
  20914. ], Camera.prototype, "layerMask", void 0);
  20915. __decorate([
  20916. BABYLON.serialize()
  20917. ], Camera.prototype, "fovMode", void 0);
  20918. __decorate([
  20919. BABYLON.serialize()
  20920. ], Camera.prototype, "cameraRigMode", void 0);
  20921. __decorate([
  20922. BABYLON.serialize()
  20923. ], Camera.prototype, "interaxialDistance", void 0);
  20924. __decorate([
  20925. BABYLON.serialize()
  20926. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  20927. return Camera;
  20928. }(BABYLON.Node));
  20929. BABYLON.Camera = Camera;
  20930. })(BABYLON || (BABYLON = {}));
  20931. //# sourceMappingURL=babylon.camera.js.map
  20932. "use strict";
  20933. var BABYLON;
  20934. (function (BABYLON) {
  20935. var RenderingManager = /** @class */ (function () {
  20936. function RenderingManager(scene) {
  20937. this._renderingGroups = new Array();
  20938. this._autoClearDepthStencil = {};
  20939. this._customOpaqueSortCompareFn = {};
  20940. this._customAlphaTestSortCompareFn = {};
  20941. this._customTransparentSortCompareFn = {};
  20942. this._renderinGroupInfo = null;
  20943. this._scene = scene;
  20944. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  20945. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  20946. }
  20947. }
  20948. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  20949. if (depth === void 0) { depth = true; }
  20950. if (stencil === void 0) { stencil = true; }
  20951. if (this._depthStencilBufferAlreadyCleaned) {
  20952. return;
  20953. }
  20954. this._scene.getEngine().clear(null, false, depth, stencil);
  20955. this._depthStencilBufferAlreadyCleaned = true;
  20956. };
  20957. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  20958. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  20959. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  20960. var info = null;
  20961. if (observable) {
  20962. if (!this._renderinGroupInfo) {
  20963. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  20964. }
  20965. info = this._renderinGroupInfo;
  20966. info.scene = this._scene;
  20967. info.camera = this._scene.activeCamera;
  20968. }
  20969. // Dispatch sprites
  20970. if (renderSprites) {
  20971. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  20972. var manager = this._scene.spriteManagers[index];
  20973. this.dispatchSprites(manager);
  20974. }
  20975. }
  20976. // Render
  20977. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  20978. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  20979. var renderingGroup = this._renderingGroups[index];
  20980. if (!renderingGroup && !observable)
  20981. continue;
  20982. var renderingGroupMask = 0;
  20983. // Fire PRECLEAR stage
  20984. if (observable && info) {
  20985. renderingGroupMask = Math.pow(2, index);
  20986. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  20987. info.renderingGroupId = index;
  20988. observable.notifyObservers(info, renderingGroupMask);
  20989. }
  20990. // Clear depth/stencil if needed
  20991. if (RenderingManager.AUTOCLEAR) {
  20992. var autoClear = this._autoClearDepthStencil[index];
  20993. if (autoClear && autoClear.autoClear) {
  20994. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  20995. }
  20996. }
  20997. if (observable && info) {
  20998. // Fire PREOPAQUE stage
  20999. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  21000. observable.notifyObservers(info, renderingGroupMask);
  21001. // Fire PRETRANSPARENT stage
  21002. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  21003. observable.notifyObservers(info, renderingGroupMask);
  21004. }
  21005. if (renderingGroup)
  21006. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  21007. // Fire POSTTRANSPARENT stage
  21008. if (observable && info) {
  21009. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  21010. observable.notifyObservers(info, renderingGroupMask);
  21011. }
  21012. }
  21013. };
  21014. RenderingManager.prototype.reset = function () {
  21015. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  21016. var renderingGroup = this._renderingGroups[index];
  21017. if (renderingGroup) {
  21018. renderingGroup.prepare();
  21019. }
  21020. }
  21021. };
  21022. RenderingManager.prototype.dispose = function () {
  21023. this.freeRenderingGroups();
  21024. this._renderingGroups.length = 0;
  21025. };
  21026. /**
  21027. * Clear the info related to rendering groups preventing retention points during dispose.
  21028. */
  21029. RenderingManager.prototype.freeRenderingGroups = function () {
  21030. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  21031. var renderingGroup = this._renderingGroups[index];
  21032. if (renderingGroup) {
  21033. renderingGroup.dispose();
  21034. }
  21035. }
  21036. };
  21037. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  21038. if (this._renderingGroups[renderingGroupId] === undefined) {
  21039. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  21040. }
  21041. };
  21042. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  21043. var renderingGroupId = spriteManager.renderingGroupId || 0;
  21044. this._prepareRenderingGroup(renderingGroupId);
  21045. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  21046. };
  21047. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  21048. var renderingGroupId = particleSystem.renderingGroupId || 0;
  21049. this._prepareRenderingGroup(renderingGroupId);
  21050. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  21051. };
  21052. /**
  21053. * @param subMesh The submesh to dispatch
  21054. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  21055. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  21056. */
  21057. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  21058. if (mesh === undefined) {
  21059. mesh = subMesh.getMesh();
  21060. }
  21061. var renderingGroupId = mesh.renderingGroupId || 0;
  21062. this._prepareRenderingGroup(renderingGroupId);
  21063. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  21064. };
  21065. /**
  21066. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  21067. * This allowed control for front to back rendering or reversly depending of the special needs.
  21068. *
  21069. * @param renderingGroupId The rendering group id corresponding to its index
  21070. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  21071. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  21072. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  21073. */
  21074. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  21075. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  21076. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  21077. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  21078. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  21079. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  21080. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  21081. if (this._renderingGroups[renderingGroupId]) {
  21082. var group = this._renderingGroups[renderingGroupId];
  21083. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  21084. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  21085. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  21086. }
  21087. };
  21088. /**
  21089. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  21090. *
  21091. * @param renderingGroupId The rendering group id corresponding to its index
  21092. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  21093. * @param depth Automatically clears depth between groups if true and autoClear is true.
  21094. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  21095. */
  21096. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  21097. if (depth === void 0) { depth = true; }
  21098. if (stencil === void 0) { stencil = true; }
  21099. this._autoClearDepthStencil[renderingGroupId] = {
  21100. autoClear: autoClearDepthStencil,
  21101. depth: depth,
  21102. stencil: stencil
  21103. };
  21104. };
  21105. /**
  21106. * The max id used for rendering groups (not included)
  21107. */
  21108. RenderingManager.MAX_RENDERINGGROUPS = 4;
  21109. /**
  21110. * The min id used for rendering groups (included)
  21111. */
  21112. RenderingManager.MIN_RENDERINGGROUPS = 0;
  21113. /**
  21114. * Used to globally prevent autoclearing scenes.
  21115. */
  21116. RenderingManager.AUTOCLEAR = true;
  21117. return RenderingManager;
  21118. }());
  21119. BABYLON.RenderingManager = RenderingManager;
  21120. })(BABYLON || (BABYLON = {}));
  21121. //# sourceMappingURL=babylon.renderingManager.js.map
  21122. "use strict";
  21123. var BABYLON;
  21124. (function (BABYLON) {
  21125. var RenderingGroup = /** @class */ (function () {
  21126. /**
  21127. * Creates a new rendering group.
  21128. * @param index The rendering group index
  21129. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  21130. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  21131. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  21132. */
  21133. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  21134. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  21135. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  21136. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  21137. this.index = index;
  21138. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  21139. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  21140. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  21141. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  21142. this._particleSystems = new BABYLON.SmartArray(256);
  21143. this._spriteManagers = new BABYLON.SmartArray(256);
  21144. this._edgesRenderers = new BABYLON.SmartArray(16);
  21145. this._scene = scene;
  21146. this.opaqueSortCompareFn = opaqueSortCompareFn;
  21147. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  21148. this.transparentSortCompareFn = transparentSortCompareFn;
  21149. }
  21150. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  21151. /**
  21152. * Set the opaque sort comparison function.
  21153. * If null the sub meshes will be render in the order they were created
  21154. */
  21155. set: function (value) {
  21156. this._opaqueSortCompareFn = value;
  21157. if (value) {
  21158. this._renderOpaque = this.renderOpaqueSorted;
  21159. }
  21160. else {
  21161. this._renderOpaque = RenderingGroup.renderUnsorted;
  21162. }
  21163. },
  21164. enumerable: true,
  21165. configurable: true
  21166. });
  21167. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  21168. /**
  21169. * Set the alpha test sort comparison function.
  21170. * If null the sub meshes will be render in the order they were created
  21171. */
  21172. set: function (value) {
  21173. this._alphaTestSortCompareFn = value;
  21174. if (value) {
  21175. this._renderAlphaTest = this.renderAlphaTestSorted;
  21176. }
  21177. else {
  21178. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  21179. }
  21180. },
  21181. enumerable: true,
  21182. configurable: true
  21183. });
  21184. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  21185. /**
  21186. * Set the transparent sort comparison function.
  21187. * If null the sub meshes will be render in the order they were created
  21188. */
  21189. set: function (value) {
  21190. if (value) {
  21191. this._transparentSortCompareFn = value;
  21192. }
  21193. else {
  21194. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  21195. }
  21196. this._renderTransparent = this.renderTransparentSorted;
  21197. },
  21198. enumerable: true,
  21199. configurable: true
  21200. });
  21201. /**
  21202. * Render all the sub meshes contained in the group.
  21203. * @param customRenderFunction Used to override the default render behaviour of the group.
  21204. * @returns true if rendered some submeshes.
  21205. */
  21206. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  21207. if (customRenderFunction) {
  21208. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  21209. return;
  21210. }
  21211. var engine = this._scene.getEngine();
  21212. // Depth only
  21213. if (this._depthOnlySubMeshes.length !== 0) {
  21214. engine.setColorWrite(false);
  21215. this._renderAlphaTest(this._depthOnlySubMeshes);
  21216. engine.setColorWrite(true);
  21217. }
  21218. // Opaque
  21219. if (this._opaqueSubMeshes.length !== 0) {
  21220. this._renderOpaque(this._opaqueSubMeshes);
  21221. }
  21222. // Alpha test
  21223. if (this._alphaTestSubMeshes.length !== 0) {
  21224. this._renderAlphaTest(this._alphaTestSubMeshes);
  21225. }
  21226. var stencilState = engine.getStencilBuffer();
  21227. engine.setStencilBuffer(false);
  21228. // Sprites
  21229. if (renderSprites) {
  21230. this._renderSprites();
  21231. }
  21232. // Particles
  21233. if (renderParticles) {
  21234. this._renderParticles(activeMeshes);
  21235. }
  21236. if (this.onBeforeTransparentRendering) {
  21237. this.onBeforeTransparentRendering();
  21238. }
  21239. // Transparent
  21240. if (this._transparentSubMeshes.length !== 0) {
  21241. this._renderTransparent(this._transparentSubMeshes);
  21242. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21243. }
  21244. // Set back stencil to false in case it changes before the edge renderer.
  21245. engine.setStencilBuffer(false);
  21246. // Edges
  21247. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  21248. this._edgesRenderers.data[edgesRendererIndex].render();
  21249. }
  21250. // Restore Stencil state.
  21251. engine.setStencilBuffer(stencilState);
  21252. };
  21253. /**
  21254. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  21255. * @param subMeshes The submeshes to render
  21256. */
  21257. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  21258. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  21259. };
  21260. /**
  21261. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  21262. * @param subMeshes The submeshes to render
  21263. */
  21264. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  21265. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  21266. };
  21267. /**
  21268. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  21269. * @param subMeshes The submeshes to render
  21270. */
  21271. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  21272. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  21273. };
  21274. /**
  21275. * Renders the submeshes in a specified order.
  21276. * @param subMeshes The submeshes to sort before render
  21277. * @param sortCompareFn The comparison function use to sort
  21278. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  21279. * @param transparent Specifies to activate blending if true
  21280. */
  21281. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  21282. var subIndex = 0;
  21283. var subMesh;
  21284. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  21285. for (; subIndex < subMeshes.length; subIndex++) {
  21286. subMesh = subMeshes.data[subIndex];
  21287. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  21288. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  21289. }
  21290. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  21291. if (sortCompareFn) {
  21292. sortedArray.sort(sortCompareFn);
  21293. }
  21294. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  21295. subMesh = sortedArray[subIndex];
  21296. if (transparent) {
  21297. var material = subMesh.getMaterial();
  21298. if (material && material.needDepthPrePass) {
  21299. var engine = material.getScene().getEngine();
  21300. engine.setColorWrite(false);
  21301. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  21302. subMesh.render(false);
  21303. engine.setColorWrite(true);
  21304. }
  21305. }
  21306. subMesh.render(transparent);
  21307. }
  21308. };
  21309. /**
  21310. * Renders the submeshes in the order they were dispatched (no sort applied).
  21311. * @param subMeshes The submeshes to render
  21312. */
  21313. RenderingGroup.renderUnsorted = function (subMeshes) {
  21314. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  21315. var submesh = subMeshes.data[subIndex];
  21316. submesh.render(false);
  21317. }
  21318. };
  21319. /**
  21320. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21321. * are rendered back to front if in the same alpha index.
  21322. *
  21323. * @param a The first submesh
  21324. * @param b The second submesh
  21325. * @returns The result of the comparison
  21326. */
  21327. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  21328. // Alpha index first
  21329. if (a._alphaIndex > b._alphaIndex) {
  21330. return 1;
  21331. }
  21332. if (a._alphaIndex < b._alphaIndex) {
  21333. return -1;
  21334. }
  21335. // Then distance to camera
  21336. return RenderingGroup.backToFrontSortCompare(a, b);
  21337. };
  21338. /**
  21339. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21340. * are rendered back to front.
  21341. *
  21342. * @param a The first submesh
  21343. * @param b The second submesh
  21344. * @returns The result of the comparison
  21345. */
  21346. RenderingGroup.backToFrontSortCompare = function (a, b) {
  21347. // Then distance to camera
  21348. if (a._distanceToCamera < b._distanceToCamera) {
  21349. return 1;
  21350. }
  21351. if (a._distanceToCamera > b._distanceToCamera) {
  21352. return -1;
  21353. }
  21354. return 0;
  21355. };
  21356. /**
  21357. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  21358. * are rendered front to back (prevent overdraw).
  21359. *
  21360. * @param a The first submesh
  21361. * @param b The second submesh
  21362. * @returns The result of the comparison
  21363. */
  21364. RenderingGroup.frontToBackSortCompare = function (a, b) {
  21365. // Then distance to camera
  21366. if (a._distanceToCamera < b._distanceToCamera) {
  21367. return -1;
  21368. }
  21369. if (a._distanceToCamera > b._distanceToCamera) {
  21370. return 1;
  21371. }
  21372. return 0;
  21373. };
  21374. /**
  21375. * Resets the different lists of submeshes to prepare a new frame.
  21376. */
  21377. RenderingGroup.prototype.prepare = function () {
  21378. this._opaqueSubMeshes.reset();
  21379. this._transparentSubMeshes.reset();
  21380. this._alphaTestSubMeshes.reset();
  21381. this._depthOnlySubMeshes.reset();
  21382. this._particleSystems.reset();
  21383. this._spriteManagers.reset();
  21384. this._edgesRenderers.reset();
  21385. };
  21386. RenderingGroup.prototype.dispose = function () {
  21387. this._opaqueSubMeshes.dispose();
  21388. this._transparentSubMeshes.dispose();
  21389. this._alphaTestSubMeshes.dispose();
  21390. this._depthOnlySubMeshes.dispose();
  21391. this._particleSystems.dispose();
  21392. this._spriteManagers.dispose();
  21393. this._edgesRenderers.dispose();
  21394. };
  21395. /**
  21396. * Inserts the submesh in its correct queue depending on its material.
  21397. * @param subMesh The submesh to dispatch
  21398. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  21399. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  21400. */
  21401. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  21402. // Get mesh and materials if not provided
  21403. if (mesh === undefined) {
  21404. mesh = subMesh.getMesh();
  21405. }
  21406. if (material === undefined) {
  21407. material = subMesh.getMaterial();
  21408. }
  21409. if (material === null || material === undefined) {
  21410. return;
  21411. }
  21412. if (material.needAlphaBlendingForMesh(mesh)) {
  21413. this._transparentSubMeshes.push(subMesh);
  21414. }
  21415. else if (material.needAlphaTesting()) {
  21416. if (material.needDepthPrePass) {
  21417. this._depthOnlySubMeshes.push(subMesh);
  21418. }
  21419. this._alphaTestSubMeshes.push(subMesh);
  21420. }
  21421. else {
  21422. if (material.needDepthPrePass) {
  21423. this._depthOnlySubMeshes.push(subMesh);
  21424. }
  21425. this._opaqueSubMeshes.push(subMesh); // Opaque
  21426. }
  21427. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  21428. this._edgesRenderers.push(mesh._edgesRenderer);
  21429. }
  21430. };
  21431. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  21432. this._spriteManagers.push(spriteManager);
  21433. };
  21434. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  21435. this._particleSystems.push(particleSystem);
  21436. };
  21437. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  21438. if (this._particleSystems.length === 0) {
  21439. return;
  21440. }
  21441. // Particles
  21442. var activeCamera = this._scene.activeCamera;
  21443. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  21444. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  21445. var particleSystem = this._particleSystems.data[particleIndex];
  21446. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  21447. continue;
  21448. }
  21449. var emitter = particleSystem.emitter;
  21450. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  21451. this._scene._activeParticles.addCount(particleSystem.render(), false);
  21452. }
  21453. }
  21454. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  21455. };
  21456. RenderingGroup.prototype._renderSprites = function () {
  21457. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  21458. return;
  21459. }
  21460. // Sprites
  21461. var activeCamera = this._scene.activeCamera;
  21462. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  21463. for (var id = 0; id < this._spriteManagers.length; id++) {
  21464. var spriteManager = this._spriteManagers.data[id];
  21465. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  21466. spriteManager.render();
  21467. }
  21468. }
  21469. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  21470. };
  21471. return RenderingGroup;
  21472. }());
  21473. BABYLON.RenderingGroup = RenderingGroup;
  21474. })(BABYLON || (BABYLON = {}));
  21475. //# sourceMappingURL=babylon.renderingGroup.js.map
  21476. "use strict";
  21477. var BABYLON;
  21478. (function (BABYLON) {
  21479. var ClickInfo = /** @class */ (function () {
  21480. function ClickInfo() {
  21481. this._singleClick = false;
  21482. this._doubleClick = false;
  21483. this._hasSwiped = false;
  21484. this._ignore = false;
  21485. }
  21486. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  21487. get: function () {
  21488. return this._singleClick;
  21489. },
  21490. set: function (b) {
  21491. this._singleClick = b;
  21492. },
  21493. enumerable: true,
  21494. configurable: true
  21495. });
  21496. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  21497. get: function () {
  21498. return this._doubleClick;
  21499. },
  21500. set: function (b) {
  21501. this._doubleClick = b;
  21502. },
  21503. enumerable: true,
  21504. configurable: true
  21505. });
  21506. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  21507. get: function () {
  21508. return this._hasSwiped;
  21509. },
  21510. set: function (b) {
  21511. this._hasSwiped = b;
  21512. },
  21513. enumerable: true,
  21514. configurable: true
  21515. });
  21516. Object.defineProperty(ClickInfo.prototype, "ignore", {
  21517. get: function () {
  21518. return this._ignore;
  21519. },
  21520. set: function (b) {
  21521. this._ignore = b;
  21522. },
  21523. enumerable: true,
  21524. configurable: true
  21525. });
  21526. return ClickInfo;
  21527. }());
  21528. /**
  21529. * This class is used by the onRenderingGroupObservable
  21530. */
  21531. var RenderingGroupInfo = /** @class */ (function () {
  21532. function RenderingGroupInfo() {
  21533. }
  21534. /**
  21535. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  21536. * This stage will be fired no matter what
  21537. */
  21538. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  21539. /**
  21540. * Called before opaque object are rendered.
  21541. * This stage will be fired only if there's 3D Opaque content to render
  21542. */
  21543. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  21544. /**
  21545. * Called after the opaque objects are rendered and before the transparent ones
  21546. * This stage will be fired only if there's 3D transparent content to render
  21547. */
  21548. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  21549. /**
  21550. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  21551. * This stage will be fired no matter what
  21552. */
  21553. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  21554. return RenderingGroupInfo;
  21555. }());
  21556. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  21557. /**
  21558. * Represents a scene to be rendered by the engine.
  21559. * @see http://doc.babylonjs.com/page.php?p=21911
  21560. */
  21561. var Scene = /** @class */ (function () {
  21562. /**
  21563. * @constructor
  21564. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  21565. */
  21566. function Scene(engine) {
  21567. // Members
  21568. this.autoClear = true;
  21569. this.autoClearDepthAndStencil = true;
  21570. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  21571. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  21572. this._forceWireframe = false;
  21573. this._forcePointsCloud = false;
  21574. this.forceShowBoundingBoxes = false;
  21575. this.animationsEnabled = true;
  21576. this.useConstantAnimationDeltaTime = false;
  21577. this.constantlyUpdateMeshUnderPointer = false;
  21578. this.hoverCursor = "pointer";
  21579. this.defaultCursor = "";
  21580. /**
  21581. * This is used to call preventDefault() on pointer down
  21582. * in order to block unwanted artifacts like system double clicks
  21583. */
  21584. this.preventDefaultOnPointerDown = true;
  21585. // Metadata
  21586. this.metadata = null;
  21587. /**
  21588. * An event triggered when the scene is disposed.
  21589. * @type {BABYLON.Observable}
  21590. */
  21591. this.onDisposeObservable = new BABYLON.Observable();
  21592. /**
  21593. * An event triggered before rendering the scene (right after animations and physics)
  21594. * @type {BABYLON.Observable}
  21595. */
  21596. this.onBeforeRenderObservable = new BABYLON.Observable();
  21597. /**
  21598. * An event triggered after rendering the scene
  21599. * @type {BABYLON.Observable}
  21600. */
  21601. this.onAfterRenderObservable = new BABYLON.Observable();
  21602. /**
  21603. * An event triggered before animating the scene
  21604. * @type {BABYLON.Observable}
  21605. */
  21606. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  21607. /**
  21608. * An event triggered after animations processing
  21609. * @type {BABYLON.Observable}
  21610. */
  21611. this.onAfterAnimationsObservable = new BABYLON.Observable();
  21612. /**
  21613. * An event triggered before draw calls are ready to be sent
  21614. * @type {BABYLON.Observable}
  21615. */
  21616. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  21617. /**
  21618. * An event triggered after draw calls have been sent
  21619. * @type {BABYLON.Observable}
  21620. */
  21621. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  21622. /**
  21623. * An event triggered when physic simulation is about to be run
  21624. * @type {BABYLON.Observable}
  21625. */
  21626. this.onBeforePhysicsObservable = new BABYLON.Observable();
  21627. /**
  21628. * An event triggered when physic simulation has been done
  21629. * @type {BABYLON.Observable}
  21630. */
  21631. this.onAfterPhysicsObservable = new BABYLON.Observable();
  21632. /**
  21633. * An event triggered when the scene is ready
  21634. * @type {BABYLON.Observable}
  21635. */
  21636. this.onReadyObservable = new BABYLON.Observable();
  21637. /**
  21638. * An event triggered before rendering a camera
  21639. * @type {BABYLON.Observable}
  21640. */
  21641. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  21642. /**
  21643. * An event triggered after rendering a camera
  21644. * @type {BABYLON.Observable}
  21645. */
  21646. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  21647. /**
  21648. * An event triggered when active meshes evaluation is about to start
  21649. * @type {BABYLON.Observable}
  21650. */
  21651. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21652. /**
  21653. * An event triggered when active meshes evaluation is done
  21654. * @type {BABYLON.Observable}
  21655. */
  21656. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  21657. /**
  21658. * An event triggered when particles rendering is about to start
  21659. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21660. * @type {BABYLON.Observable}
  21661. */
  21662. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  21663. /**
  21664. * An event triggered when particles rendering is done
  21665. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  21666. * @type {BABYLON.Observable}
  21667. */
  21668. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  21669. /**
  21670. * An event triggered when sprites rendering is about to start
  21671. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21672. * @type {BABYLON.Observable}
  21673. */
  21674. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  21675. /**
  21676. * An event triggered when sprites rendering is done
  21677. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  21678. * @type {BABYLON.Observable}
  21679. */
  21680. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  21681. /**
  21682. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  21683. * @type {BABYLON.Observable}
  21684. */
  21685. this.onDataLoadedObservable = new BABYLON.Observable();
  21686. /**
  21687. * An event triggered when a camera is created
  21688. * @type {BABYLON.Observable}
  21689. */
  21690. this.onNewCameraAddedObservable = new BABYLON.Observable();
  21691. /**
  21692. * An event triggered when a camera is removed
  21693. * @type {BABYLON.Observable}
  21694. */
  21695. this.onCameraRemovedObservable = new BABYLON.Observable();
  21696. /**
  21697. * An event triggered when a light is created
  21698. * @type {BABYLON.Observable}
  21699. */
  21700. this.onNewLightAddedObservable = new BABYLON.Observable();
  21701. /**
  21702. * An event triggered when a light is removed
  21703. * @type {BABYLON.Observable}
  21704. */
  21705. this.onLightRemovedObservable = new BABYLON.Observable();
  21706. /**
  21707. * An event triggered when a geometry is created
  21708. * @type {BABYLON.Observable}
  21709. */
  21710. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  21711. /**
  21712. * An event triggered when a geometry is removed
  21713. * @type {BABYLON.Observable}
  21714. */
  21715. this.onGeometryRemovedObservable = new BABYLON.Observable();
  21716. /**
  21717. * An event triggered when a transform node is created
  21718. * @type {BABYLON.Observable}
  21719. */
  21720. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  21721. /**
  21722. * An event triggered when a transform node is removed
  21723. * @type {BABYLON.Observable}
  21724. */
  21725. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  21726. /**
  21727. * An event triggered when a mesh is created
  21728. * @type {BABYLON.Observable}
  21729. */
  21730. this.onNewMeshAddedObservable = new BABYLON.Observable();
  21731. /**
  21732. * An event triggered when a mesh is removed
  21733. * @type {BABYLON.Observable}
  21734. */
  21735. this.onMeshRemovedObservable = new BABYLON.Observable();
  21736. /**
  21737. * An event triggered when render targets are about to be rendered
  21738. * Can happen multiple times per frame.
  21739. * @type {BABYLON.Observable}
  21740. */
  21741. this.OnBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  21742. /**
  21743. * An event triggered when render targets were rendered.
  21744. * Can happen multiple times per frame.
  21745. * @type {BABYLON.Observable}
  21746. */
  21747. this.OnAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  21748. /**
  21749. * An event triggered before calculating deterministic simulation step
  21750. * @type {BABYLON.Observable}
  21751. */
  21752. this.onBeforeStepObservable = new BABYLON.Observable();
  21753. /**
  21754. * An event triggered after calculating deterministic simulation step
  21755. * @type {BABYLON.Observable}
  21756. */
  21757. this.onAfterStepObservable = new BABYLON.Observable();
  21758. /**
  21759. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  21760. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  21761. * 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)
  21762. */
  21763. this.onRenderingGroupObservable = new BABYLON.Observable();
  21764. // Animations
  21765. this.animations = [];
  21766. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  21767. /**
  21768. * 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).
  21769. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  21770. */
  21771. this.onPrePointerObservable = new BABYLON.Observable();
  21772. /**
  21773. * Observable event triggered each time an input event is received from the rendering canvas
  21774. */
  21775. this.onPointerObservable = new BABYLON.Observable();
  21776. this._meshPickProceed = false;
  21777. this._currentPickResult = null;
  21778. this._previousPickResult = null;
  21779. this._totalPointersPressed = 0;
  21780. this._doubleClickOccured = false;
  21781. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  21782. this.cameraToUseForPointers = null;
  21783. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  21784. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  21785. this._startingPointerTime = 0;
  21786. this._previousStartingPointerTime = 0;
  21787. // Deterministic lockstep
  21788. this._timeAccumulator = 0;
  21789. this._currentStepId = 0;
  21790. this._currentInternalStep = 0;
  21791. // Keyboard
  21792. /**
  21793. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  21794. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  21795. */
  21796. this.onPreKeyboardObservable = new BABYLON.Observable();
  21797. /**
  21798. * Observable event triggered each time an keyboard event is received from the hosting window
  21799. */
  21800. this.onKeyboardObservable = new BABYLON.Observable();
  21801. // Coordinate system
  21802. /**
  21803. * use right-handed coordinate system on this scene.
  21804. * @type {boolean}
  21805. */
  21806. this._useRightHandedSystem = false;
  21807. // Fog
  21808. this._fogEnabled = true;
  21809. this._fogMode = Scene.FOGMODE_NONE;
  21810. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  21811. this.fogDensity = 0.1;
  21812. this.fogStart = 0;
  21813. this.fogEnd = 1000.0;
  21814. // Lights
  21815. /**
  21816. * is shadow enabled on this scene.
  21817. * @type {boolean}
  21818. */
  21819. this._shadowsEnabled = true;
  21820. /**
  21821. * is light enabled on this scene.
  21822. * @type {boolean}
  21823. */
  21824. this._lightsEnabled = true;
  21825. /**
  21826. * All of the lights added to this scene.
  21827. * @see BABYLON.Light
  21828. * @type {BABYLON.Light[]}
  21829. */
  21830. this.lights = new Array();
  21831. // Cameras
  21832. /** All of the cameras added to this scene. */
  21833. this.cameras = new Array();
  21834. /** All of the active cameras added to this scene. */
  21835. this.activeCameras = new Array();
  21836. // Meshes
  21837. /**
  21838. * All of the tranform nodes added to this scene.
  21839. * @see BABYLON.TransformNode
  21840. * @type {BABYLON.TransformNode[]}
  21841. */
  21842. this.transformNodes = new Array();
  21843. /**
  21844. * All of the (abstract) meshes added to this scene.
  21845. * @see BABYLON.AbstractMesh
  21846. * @type {BABYLON.AbstractMesh[]}
  21847. */
  21848. this.meshes = new Array();
  21849. /**
  21850. * All of the animation groups added to this scene.
  21851. * @see BABYLON.AnimationGroup
  21852. * @type {BABYLON.AnimationGroup[]}
  21853. */
  21854. this.animationGroups = new Array();
  21855. // Geometries
  21856. this._geometries = new Array();
  21857. this.materials = new Array();
  21858. this.multiMaterials = new Array();
  21859. // Textures
  21860. this._texturesEnabled = true;
  21861. this.textures = new Array();
  21862. // Particles
  21863. this.particlesEnabled = true;
  21864. this.particleSystems = new Array();
  21865. // Sprites
  21866. this.spritesEnabled = true;
  21867. this.spriteManagers = new Array();
  21868. /**
  21869. * The list of layers (background and foreground) of the scene.
  21870. */
  21871. this.layers = new Array();
  21872. /**
  21873. * The list of effect layers (highlights/glow) contained in the scene.
  21874. */
  21875. this.effectLayers = new Array();
  21876. // Skeletons
  21877. this._skeletonsEnabled = true;
  21878. this.skeletons = new Array();
  21879. // Morph targets
  21880. this.morphTargetManagers = new Array();
  21881. // Lens flares
  21882. this.lensFlaresEnabled = true;
  21883. this.lensFlareSystems = new Array();
  21884. // Collisions
  21885. this.collisionsEnabled = true;
  21886. /** Defines the gravity applied to this scene */
  21887. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  21888. // Postprocesses
  21889. this.postProcesses = new Array();
  21890. this.postProcessesEnabled = true;
  21891. // Customs render targets
  21892. this.renderTargetsEnabled = true;
  21893. this.dumpNextRenderTargets = false;
  21894. this.customRenderTargets = new Array();
  21895. // Imported meshes
  21896. this.importedMeshesFiles = new Array();
  21897. // Probes
  21898. this.probesEnabled = true;
  21899. this.reflectionProbes = new Array();
  21900. this._actionManagers = new Array();
  21901. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  21902. // Procedural textures
  21903. this.proceduralTexturesEnabled = true;
  21904. this._proceduralTextures = new Array();
  21905. this.soundTracks = new Array();
  21906. this._audioEnabled = true;
  21907. this._headphone = false;
  21908. // Performance counters
  21909. this._totalVertices = new BABYLON.PerfCounter();
  21910. this._activeIndices = new BABYLON.PerfCounter();
  21911. this._activeParticles = new BABYLON.PerfCounter();
  21912. this._activeBones = new BABYLON.PerfCounter();
  21913. this._animationTime = 0;
  21914. this.animationTimeScale = 1;
  21915. this._renderId = 0;
  21916. this._executeWhenReadyTimeoutId = -1;
  21917. this._intermediateRendering = false;
  21918. this._viewUpdateFlag = -1;
  21919. this._projectionUpdateFlag = -1;
  21920. this._alternateViewUpdateFlag = -1;
  21921. this._alternateProjectionUpdateFlag = -1;
  21922. this._toBeDisposed = new BABYLON.SmartArray(256);
  21923. this._activeRequests = new Array();
  21924. this._pendingData = new Array();
  21925. this._isDisposed = false;
  21926. this.dispatchAllSubMeshesOfActiveMeshes = false;
  21927. this._activeMeshes = new BABYLON.SmartArray(256);
  21928. this._processedMaterials = new BABYLON.SmartArray(256);
  21929. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  21930. this._activeParticleSystems = new BABYLON.SmartArray(256);
  21931. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  21932. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  21933. this._activeAnimatables = new Array();
  21934. this._transformMatrix = BABYLON.Matrix.Zero();
  21935. this._useAlternateCameraConfiguration = false;
  21936. this._alternateRendering = false;
  21937. this.requireLightSorting = false;
  21938. this._depthRenderer = {};
  21939. this._activeMeshesFrozen = false;
  21940. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  21941. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  21942. this._engine.scenes.push(this);
  21943. this._uid = null;
  21944. this._renderingManager = new BABYLON.RenderingManager(this);
  21945. this.postProcessManager = new BABYLON.PostProcessManager(this);
  21946. if (BABYLON.OutlineRenderer) {
  21947. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  21948. }
  21949. if (BABYLON.Tools.IsWindowObjectExist()) {
  21950. this.attachControl();
  21951. }
  21952. //simplification queue
  21953. if (BABYLON.SimplificationQueue) {
  21954. this.simplificationQueue = new BABYLON.SimplificationQueue();
  21955. }
  21956. //collision coordinator initialization. For now legacy per default.
  21957. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  21958. // Uniform Buffer
  21959. this._createUbo();
  21960. // Default Image processing definition.
  21961. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  21962. }
  21963. Object.defineProperty(Scene, "FOGMODE_NONE", {
  21964. /** The fog is deactivated */
  21965. get: function () {
  21966. return Scene._FOGMODE_NONE;
  21967. },
  21968. enumerable: true,
  21969. configurable: true
  21970. });
  21971. Object.defineProperty(Scene, "FOGMODE_EXP", {
  21972. /** The fog density is following an exponential function */
  21973. get: function () {
  21974. return Scene._FOGMODE_EXP;
  21975. },
  21976. enumerable: true,
  21977. configurable: true
  21978. });
  21979. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  21980. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  21981. get: function () {
  21982. return Scene._FOGMODE_EXP2;
  21983. },
  21984. enumerable: true,
  21985. configurable: true
  21986. });
  21987. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  21988. /** The fog density is following a linear function. */
  21989. get: function () {
  21990. return Scene._FOGMODE_LINEAR;
  21991. },
  21992. enumerable: true,
  21993. configurable: true
  21994. });
  21995. Object.defineProperty(Scene.prototype, "environmentTexture", {
  21996. /**
  21997. * Texture used in all pbr material as the reflection texture.
  21998. * As in the majority of the scene they are the same (exception for multi room and so on),
  21999. * this is easier to reference from here than from all the materials.
  22000. */
  22001. get: function () {
  22002. return this._environmentTexture;
  22003. },
  22004. /**
  22005. * Texture used in all pbr material as the reflection texture.
  22006. * As in the majority of the scene they are the same (exception for multi room and so on),
  22007. * this is easier to set here than in all the materials.
  22008. */
  22009. set: function (value) {
  22010. if (this._environmentTexture === value) {
  22011. return;
  22012. }
  22013. this._environmentTexture = value;
  22014. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22015. },
  22016. enumerable: true,
  22017. configurable: true
  22018. });
  22019. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  22020. /**
  22021. * Default image processing configuration used either in the rendering
  22022. * Forward main pass or through the imageProcessingPostProcess if present.
  22023. * As in the majority of the scene they are the same (exception for multi camera),
  22024. * this is easier to reference from here than from all the materials and post process.
  22025. *
  22026. * No setter as we it is a shared configuration, you can set the values instead.
  22027. */
  22028. get: function () {
  22029. return this._imageProcessingConfiguration;
  22030. },
  22031. enumerable: true,
  22032. configurable: true
  22033. });
  22034. Object.defineProperty(Scene.prototype, "forceWireframe", {
  22035. get: function () {
  22036. return this._forceWireframe;
  22037. },
  22038. set: function (value) {
  22039. if (this._forceWireframe === value) {
  22040. return;
  22041. }
  22042. this._forceWireframe = value;
  22043. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22044. },
  22045. enumerable: true,
  22046. configurable: true
  22047. });
  22048. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  22049. get: function () {
  22050. return this._forcePointsCloud;
  22051. },
  22052. set: function (value) {
  22053. if (this._forcePointsCloud === value) {
  22054. return;
  22055. }
  22056. this._forcePointsCloud = value;
  22057. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22058. },
  22059. enumerable: true,
  22060. configurable: true
  22061. });
  22062. Object.defineProperty(Scene.prototype, "onDispose", {
  22063. /** A function to be executed when this scene is disposed. */
  22064. set: function (callback) {
  22065. if (this._onDisposeObserver) {
  22066. this.onDisposeObservable.remove(this._onDisposeObserver);
  22067. }
  22068. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  22069. },
  22070. enumerable: true,
  22071. configurable: true
  22072. });
  22073. Object.defineProperty(Scene.prototype, "beforeRender", {
  22074. /** A function to be executed before rendering this scene */
  22075. set: function (callback) {
  22076. if (this._onBeforeRenderObserver) {
  22077. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  22078. }
  22079. if (callback) {
  22080. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  22081. }
  22082. },
  22083. enumerable: true,
  22084. configurable: true
  22085. });
  22086. Object.defineProperty(Scene.prototype, "afterRender", {
  22087. /** A function to be executed after rendering this scene */
  22088. set: function (callback) {
  22089. if (this._onAfterRenderObserver) {
  22090. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  22091. }
  22092. if (callback) {
  22093. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  22094. }
  22095. },
  22096. enumerable: true,
  22097. configurable: true
  22098. });
  22099. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  22100. set: function (callback) {
  22101. if (this._onBeforeCameraRenderObserver) {
  22102. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  22103. }
  22104. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  22105. },
  22106. enumerable: true,
  22107. configurable: true
  22108. });
  22109. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  22110. set: function (callback) {
  22111. if (this._onAfterCameraRenderObserver) {
  22112. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  22113. }
  22114. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  22115. },
  22116. enumerable: true,
  22117. configurable: true
  22118. });
  22119. Object.defineProperty(Scene.prototype, "gamepadManager", {
  22120. get: function () {
  22121. if (!this._gamepadManager) {
  22122. this._gamepadManager = new BABYLON.GamepadManager(this);
  22123. }
  22124. return this._gamepadManager;
  22125. },
  22126. enumerable: true,
  22127. configurable: true
  22128. });
  22129. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  22130. get: function () {
  22131. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  22132. },
  22133. enumerable: true,
  22134. configurable: true
  22135. });
  22136. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  22137. get: function () {
  22138. return this._useRightHandedSystem;
  22139. },
  22140. set: function (value) {
  22141. if (this._useRightHandedSystem === value) {
  22142. return;
  22143. }
  22144. this._useRightHandedSystem = value;
  22145. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22146. },
  22147. enumerable: true,
  22148. configurable: true
  22149. });
  22150. Scene.prototype.setStepId = function (newStepId) {
  22151. this._currentStepId = newStepId;
  22152. };
  22153. ;
  22154. Scene.prototype.getStepId = function () {
  22155. return this._currentStepId;
  22156. };
  22157. ;
  22158. Scene.prototype.getInternalStep = function () {
  22159. return this._currentInternalStep;
  22160. };
  22161. ;
  22162. Object.defineProperty(Scene.prototype, "fogEnabled", {
  22163. get: function () {
  22164. return this._fogEnabled;
  22165. },
  22166. /**
  22167. * is fog enabled on this scene.
  22168. */
  22169. set: function (value) {
  22170. if (this._fogEnabled === value) {
  22171. return;
  22172. }
  22173. this._fogEnabled = value;
  22174. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22175. },
  22176. enumerable: true,
  22177. configurable: true
  22178. });
  22179. Object.defineProperty(Scene.prototype, "fogMode", {
  22180. get: function () {
  22181. return this._fogMode;
  22182. },
  22183. set: function (value) {
  22184. if (this._fogMode === value) {
  22185. return;
  22186. }
  22187. this._fogMode = value;
  22188. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  22189. },
  22190. enumerable: true,
  22191. configurable: true
  22192. });
  22193. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  22194. get: function () {
  22195. return this._shadowsEnabled;
  22196. },
  22197. set: function (value) {
  22198. if (this._shadowsEnabled === value) {
  22199. return;
  22200. }
  22201. this._shadowsEnabled = value;
  22202. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  22203. },
  22204. enumerable: true,
  22205. configurable: true
  22206. });
  22207. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  22208. get: function () {
  22209. return this._lightsEnabled;
  22210. },
  22211. set: function (value) {
  22212. if (this._lightsEnabled === value) {
  22213. return;
  22214. }
  22215. this._lightsEnabled = value;
  22216. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  22217. },
  22218. enumerable: true,
  22219. configurable: true
  22220. });
  22221. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  22222. /** The default material used on meshes when no material is affected */
  22223. get: function () {
  22224. if (!this._defaultMaterial) {
  22225. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  22226. }
  22227. return this._defaultMaterial;
  22228. },
  22229. /** The default material used on meshes when no material is affected */
  22230. set: function (value) {
  22231. this._defaultMaterial = value;
  22232. },
  22233. enumerable: true,
  22234. configurable: true
  22235. });
  22236. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  22237. get: function () {
  22238. return this._texturesEnabled;
  22239. },
  22240. set: function (value) {
  22241. if (this._texturesEnabled === value) {
  22242. return;
  22243. }
  22244. this._texturesEnabled = value;
  22245. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  22246. },
  22247. enumerable: true,
  22248. configurable: true
  22249. });
  22250. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  22251. get: function () {
  22252. return this._skeletonsEnabled;
  22253. },
  22254. set: function (value) {
  22255. if (this._skeletonsEnabled === value) {
  22256. return;
  22257. }
  22258. this._skeletonsEnabled = value;
  22259. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  22260. },
  22261. enumerable: true,
  22262. configurable: true
  22263. });
  22264. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  22265. get: function () {
  22266. if (!this._postProcessRenderPipelineManager) {
  22267. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  22268. }
  22269. return this._postProcessRenderPipelineManager;
  22270. },
  22271. enumerable: true,
  22272. configurable: true
  22273. });
  22274. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  22275. get: function () {
  22276. if (!this._mainSoundTrack) {
  22277. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  22278. }
  22279. return this._mainSoundTrack;
  22280. },
  22281. enumerable: true,
  22282. configurable: true
  22283. });
  22284. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  22285. get: function () {
  22286. return this._alternateRendering;
  22287. },
  22288. enumerable: true,
  22289. configurable: true
  22290. });
  22291. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  22292. get: function () {
  22293. return this._frustumPlanes;
  22294. },
  22295. enumerable: true,
  22296. configurable: true
  22297. });
  22298. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  22299. /**
  22300. * Gets the current geometry buffer associated to the scene.
  22301. */
  22302. get: function () {
  22303. return this._geometryBufferRenderer;
  22304. },
  22305. /**
  22306. * Sets the current geometry buffer for the scene.
  22307. */
  22308. set: function (geometryBufferRenderer) {
  22309. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  22310. this._geometryBufferRenderer = geometryBufferRenderer;
  22311. }
  22312. },
  22313. enumerable: true,
  22314. configurable: true
  22315. });
  22316. Object.defineProperty(Scene.prototype, "debugLayer", {
  22317. // Properties
  22318. get: function () {
  22319. if (!this._debugLayer) {
  22320. this._debugLayer = new BABYLON.DebugLayer(this);
  22321. }
  22322. return this._debugLayer;
  22323. },
  22324. enumerable: true,
  22325. configurable: true
  22326. });
  22327. Object.defineProperty(Scene.prototype, "workerCollisions", {
  22328. get: function () {
  22329. return this._workerCollisions;
  22330. },
  22331. set: function (enabled) {
  22332. if (!BABYLON.CollisionCoordinatorLegacy) {
  22333. return;
  22334. }
  22335. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  22336. this._workerCollisions = enabled;
  22337. if (this.collisionCoordinator) {
  22338. this.collisionCoordinator.destroy();
  22339. }
  22340. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  22341. this.collisionCoordinator.init(this);
  22342. },
  22343. enumerable: true,
  22344. configurable: true
  22345. });
  22346. Object.defineProperty(Scene.prototype, "selectionOctree", {
  22347. get: function () {
  22348. return this._selectionOctree;
  22349. },
  22350. enumerable: true,
  22351. configurable: true
  22352. });
  22353. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  22354. /**
  22355. * The mesh that is currently under the pointer.
  22356. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  22357. */
  22358. get: function () {
  22359. return this._pointerOverMesh;
  22360. },
  22361. enumerable: true,
  22362. configurable: true
  22363. });
  22364. Object.defineProperty(Scene.prototype, "pointerX", {
  22365. /**
  22366. * Current on-screen X position of the pointer
  22367. * @return {number} X position of the pointer
  22368. */
  22369. get: function () {
  22370. return this._pointerX;
  22371. },
  22372. enumerable: true,
  22373. configurable: true
  22374. });
  22375. Object.defineProperty(Scene.prototype, "pointerY", {
  22376. /**
  22377. * Current on-screen Y position of the pointer
  22378. * @return {number} Y position of the pointer
  22379. */
  22380. get: function () {
  22381. return this._pointerY;
  22382. },
  22383. enumerable: true,
  22384. configurable: true
  22385. });
  22386. Scene.prototype.getCachedMaterial = function () {
  22387. return this._cachedMaterial;
  22388. };
  22389. Scene.prototype.getCachedEffect = function () {
  22390. return this._cachedEffect;
  22391. };
  22392. Scene.prototype.getCachedVisibility = function () {
  22393. return this._cachedVisibility;
  22394. };
  22395. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  22396. if (visibility === void 0) { visibility = 1; }
  22397. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  22398. };
  22399. Scene.prototype.getBoundingBoxRenderer = function () {
  22400. if (!this._boundingBoxRenderer) {
  22401. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  22402. }
  22403. return this._boundingBoxRenderer;
  22404. };
  22405. Scene.prototype.getOutlineRenderer = function () {
  22406. return this._outlineRenderer;
  22407. };
  22408. Scene.prototype.getEngine = function () {
  22409. return this._engine;
  22410. };
  22411. Scene.prototype.getTotalVertices = function () {
  22412. return this._totalVertices.current;
  22413. };
  22414. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  22415. get: function () {
  22416. return this._totalVertices;
  22417. },
  22418. enumerable: true,
  22419. configurable: true
  22420. });
  22421. Scene.prototype.getActiveIndices = function () {
  22422. return this._activeIndices.current;
  22423. };
  22424. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  22425. get: function () {
  22426. return this._activeIndices;
  22427. },
  22428. enumerable: true,
  22429. configurable: true
  22430. });
  22431. Scene.prototype.getActiveParticles = function () {
  22432. return this._activeParticles.current;
  22433. };
  22434. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  22435. get: function () {
  22436. return this._activeParticles;
  22437. },
  22438. enumerable: true,
  22439. configurable: true
  22440. });
  22441. Scene.prototype.getActiveBones = function () {
  22442. return this._activeBones.current;
  22443. };
  22444. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  22445. get: function () {
  22446. return this._activeBones;
  22447. },
  22448. enumerable: true,
  22449. configurable: true
  22450. });
  22451. // Stats
  22452. Scene.prototype.getInterFramePerfCounter = function () {
  22453. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22454. return 0;
  22455. };
  22456. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  22457. get: function () {
  22458. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22459. return null;
  22460. },
  22461. enumerable: true,
  22462. configurable: true
  22463. });
  22464. Scene.prototype.getLastFrameDuration = function () {
  22465. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  22466. return 0;
  22467. };
  22468. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  22469. get: function () {
  22470. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  22471. return null;
  22472. },
  22473. enumerable: true,
  22474. configurable: true
  22475. });
  22476. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  22477. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  22478. return 0;
  22479. };
  22480. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  22481. get: function () {
  22482. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22483. return null;
  22484. },
  22485. enumerable: true,
  22486. configurable: true
  22487. });
  22488. Scene.prototype.getActiveMeshes = function () {
  22489. return this._activeMeshes;
  22490. };
  22491. Scene.prototype.getRenderTargetsDuration = function () {
  22492. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  22493. return 0;
  22494. };
  22495. Scene.prototype.getRenderDuration = function () {
  22496. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  22497. return 0;
  22498. };
  22499. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  22500. get: function () {
  22501. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22502. return null;
  22503. },
  22504. enumerable: true,
  22505. configurable: true
  22506. });
  22507. Scene.prototype.getParticlesDuration = function () {
  22508. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  22509. return 0;
  22510. };
  22511. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  22512. get: function () {
  22513. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  22514. return null;
  22515. },
  22516. enumerable: true,
  22517. configurable: true
  22518. });
  22519. Scene.prototype.getSpritesDuration = function () {
  22520. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  22521. return 0;
  22522. };
  22523. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  22524. get: function () {
  22525. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  22526. return null;
  22527. },
  22528. enumerable: true,
  22529. configurable: true
  22530. });
  22531. Scene.prototype.getAnimationRatio = function () {
  22532. return this._animationRatio;
  22533. };
  22534. Scene.prototype.getRenderId = function () {
  22535. return this._renderId;
  22536. };
  22537. Scene.prototype.incrementRenderId = function () {
  22538. this._renderId++;
  22539. };
  22540. Scene.prototype._updatePointerPosition = function (evt) {
  22541. var canvasRect = this._engine.getRenderingCanvasClientRect();
  22542. if (!canvasRect) {
  22543. return;
  22544. }
  22545. this._pointerX = evt.clientX - canvasRect.left;
  22546. this._pointerY = evt.clientY - canvasRect.top;
  22547. this._unTranslatedPointerX = this._pointerX;
  22548. this._unTranslatedPointerY = this._pointerY;
  22549. };
  22550. Scene.prototype._createUbo = function () {
  22551. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22552. this._sceneUbo.addUniform("viewProjection", 16);
  22553. this._sceneUbo.addUniform("view", 16);
  22554. };
  22555. Scene.prototype._createAlternateUbo = function () {
  22556. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  22557. this._alternateSceneUbo.addUniform("viewProjection", 16);
  22558. this._alternateSceneUbo.addUniform("view", 16);
  22559. };
  22560. // Pointers handling
  22561. /**
  22562. * Use this method to simulate a pointer move on a mesh
  22563. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22564. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22565. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22566. */
  22567. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  22568. var evt = new PointerEvent("pointermove", pointerEventInit);
  22569. return this._processPointerMove(pickResult, evt);
  22570. };
  22571. Scene.prototype._processPointerMove = function (pickResult, evt) {
  22572. var canvas = this._engine.getRenderingCanvas();
  22573. if (!canvas) {
  22574. return this;
  22575. }
  22576. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22577. this.setPointerOverSprite(null);
  22578. this.setPointerOverMesh(pickResult.pickedMesh);
  22579. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  22580. if (this._pointerOverMesh.actionManager.hoverCursor) {
  22581. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  22582. }
  22583. else {
  22584. canvas.style.cursor = this.hoverCursor;
  22585. }
  22586. }
  22587. else {
  22588. canvas.style.cursor = this.defaultCursor;
  22589. }
  22590. }
  22591. else {
  22592. this.setPointerOverMesh(null);
  22593. // Sprites
  22594. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  22595. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22596. this.setPointerOverSprite(pickResult.pickedSprite);
  22597. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  22598. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  22599. }
  22600. else {
  22601. canvas.style.cursor = this.hoverCursor;
  22602. }
  22603. }
  22604. else {
  22605. this.setPointerOverSprite(null);
  22606. // Restore pointer
  22607. canvas.style.cursor = this.defaultCursor;
  22608. }
  22609. }
  22610. if (pickResult) {
  22611. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22612. if (this.onPointerMove) {
  22613. this.onPointerMove(evt, pickResult, type);
  22614. }
  22615. if (this.onPointerObservable.hasObservers()) {
  22616. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22617. this.onPointerObservable.notifyObservers(pi, type);
  22618. }
  22619. }
  22620. return this;
  22621. };
  22622. /**
  22623. * Use this method to simulate a pointer down on a mesh
  22624. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22625. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22626. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22627. */
  22628. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  22629. var evt = new PointerEvent("pointerdown", pointerEventInit);
  22630. return this._processPointerDown(pickResult, evt);
  22631. };
  22632. Scene.prototype._processPointerDown = function (pickResult, evt) {
  22633. var _this = this;
  22634. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  22635. this._pickedDownMesh = pickResult.pickedMesh;
  22636. var actionManager = pickResult.pickedMesh.actionManager;
  22637. if (actionManager) {
  22638. if (actionManager.hasPickTriggers) {
  22639. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22640. switch (evt.button) {
  22641. case 0:
  22642. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22643. break;
  22644. case 1:
  22645. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22646. break;
  22647. case 2:
  22648. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22649. break;
  22650. }
  22651. }
  22652. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  22653. window.setTimeout(function () {
  22654. 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);
  22655. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  22656. if (_this._totalPointersPressed !== 0 &&
  22657. ((new Date().getTime() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  22658. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  22659. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  22660. _this._startingPointerTime = 0;
  22661. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22662. }
  22663. }
  22664. }, Scene.LongPressDelay);
  22665. }
  22666. }
  22667. }
  22668. if (pickResult) {
  22669. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22670. if (this.onPointerDown) {
  22671. this.onPointerDown(evt, pickResult, type);
  22672. }
  22673. if (this.onPointerObservable.hasObservers()) {
  22674. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22675. this.onPointerObservable.notifyObservers(pi, type);
  22676. }
  22677. }
  22678. return this;
  22679. };
  22680. /**
  22681. * Use this method to simulate a pointer up on a mesh
  22682. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  22683. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  22684. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  22685. */
  22686. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  22687. var evt = new PointerEvent("pointerup", pointerEventInit);
  22688. var clickInfo = new ClickInfo();
  22689. clickInfo.singleClick = true;
  22690. clickInfo.ignore = true;
  22691. return this._processPointerUp(pickResult, evt, clickInfo);
  22692. };
  22693. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  22694. if (pickResult && pickResult && pickResult.pickedMesh) {
  22695. this._pickedUpMesh = pickResult.pickedMesh;
  22696. if (this._pickedDownMesh === this._pickedUpMesh) {
  22697. if (this.onPointerPick) {
  22698. this.onPointerPick(evt, pickResult);
  22699. }
  22700. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  22701. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  22702. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  22703. this.onPointerObservable.notifyObservers(pi, type_1);
  22704. }
  22705. }
  22706. if (pickResult.pickedMesh.actionManager) {
  22707. if (clickInfo.ignore) {
  22708. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22709. }
  22710. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  22711. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22712. }
  22713. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22714. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  22715. }
  22716. }
  22717. }
  22718. if (this._pickedDownMesh &&
  22719. this._pickedDownMesh.actionManager &&
  22720. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  22721. this._pickedDownMesh !== this._pickedUpMesh) {
  22722. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  22723. }
  22724. var type = BABYLON.PointerEventTypes.POINTERUP;
  22725. if (this.onPointerObservable.hasObservers()) {
  22726. if (!clickInfo.ignore) {
  22727. if (!clickInfo.hasSwiped) {
  22728. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22729. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  22730. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  22731. this.onPointerObservable.notifyObservers(pi, type_2);
  22732. }
  22733. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22734. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22735. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  22736. this.onPointerObservable.notifyObservers(pi, type_3);
  22737. }
  22738. }
  22739. }
  22740. else {
  22741. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  22742. this.onPointerObservable.notifyObservers(pi, type);
  22743. }
  22744. }
  22745. if (this.onPointerUp) {
  22746. this.onPointerUp(evt, pickResult, type);
  22747. }
  22748. return this;
  22749. };
  22750. /**
  22751. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  22752. * @param attachUp defines if you want to attach events to pointerup
  22753. * @param attachDown defines if you want to attach events to pointerdown
  22754. * @param attachMove defines if you want to attach events to pointermove
  22755. */
  22756. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  22757. var _this = this;
  22758. if (attachUp === void 0) { attachUp = true; }
  22759. if (attachDown === void 0) { attachDown = true; }
  22760. if (attachMove === void 0) { attachMove = true; }
  22761. this._initActionManager = function (act, clickInfo) {
  22762. if (!_this._meshPickProceed) {
  22763. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22764. _this._currentPickResult = pickResult;
  22765. if (pickResult) {
  22766. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  22767. }
  22768. _this._meshPickProceed = true;
  22769. }
  22770. return act;
  22771. };
  22772. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  22773. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  22774. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  22775. btn !== _this._previousButtonPressed) {
  22776. _this._doubleClickOccured = false;
  22777. clickInfo.singleClick = true;
  22778. clickInfo.ignore = false;
  22779. cb(clickInfo, _this._currentPickResult);
  22780. }
  22781. };
  22782. this._initClickEvent = function (obs1, obs2, evt, cb) {
  22783. var clickInfo = new ClickInfo();
  22784. _this._currentPickResult = null;
  22785. var act = null;
  22786. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  22787. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  22788. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22789. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  22790. act = _this._initActionManager(act, clickInfo);
  22791. if (act)
  22792. checkPicking = act.hasPickTriggers;
  22793. }
  22794. if (checkPicking) {
  22795. var btn = evt.button;
  22796. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  22797. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  22798. if (!clickInfo.hasSwiped) {
  22799. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  22800. if (!checkSingleClickImmediately) {
  22801. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  22802. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22803. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22804. act = _this._initActionManager(act, clickInfo);
  22805. if (act)
  22806. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22807. }
  22808. }
  22809. if (checkSingleClickImmediately) {
  22810. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  22811. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  22812. btn !== _this._previousButtonPressed) {
  22813. clickInfo.singleClick = true;
  22814. cb(clickInfo, _this._currentPickResult);
  22815. }
  22816. }
  22817. else {
  22818. // wait that no double click has been raised during the double click delay
  22819. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22820. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  22821. }
  22822. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  22823. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  22824. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  22825. act = _this._initActionManager(act, clickInfo);
  22826. if (act)
  22827. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  22828. }
  22829. if (checkDoubleClick) {
  22830. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  22831. if (btn === _this._previousButtonPressed &&
  22832. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  22833. !_this._doubleClickOccured) {
  22834. // pointer has not moved for 2 clicks, it's a double click
  22835. if (!clickInfo.hasSwiped &&
  22836. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  22837. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  22838. _this._previousStartingPointerTime = 0;
  22839. _this._doubleClickOccured = true;
  22840. clickInfo.doubleClick = true;
  22841. clickInfo.ignore = false;
  22842. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  22843. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22844. }
  22845. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22846. cb(clickInfo, _this._currentPickResult);
  22847. }
  22848. else {
  22849. _this._doubleClickOccured = false;
  22850. _this._previousStartingPointerTime = _this._startingPointerTime;
  22851. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22852. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22853. _this._previousButtonPressed = btn;
  22854. if (Scene.ExclusiveDoubleClickMode) {
  22855. if (_this._previousDelayedSimpleClickTimeout) {
  22856. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  22857. }
  22858. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  22859. cb(clickInfo, _this._previousPickResult);
  22860. }
  22861. else {
  22862. cb(clickInfo, _this._currentPickResult);
  22863. }
  22864. }
  22865. }
  22866. else {
  22867. _this._doubleClickOccured = false;
  22868. _this._previousStartingPointerTime = _this._startingPointerTime;
  22869. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  22870. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  22871. _this._previousButtonPressed = btn;
  22872. }
  22873. }
  22874. }
  22875. }
  22876. clickInfo.ignore = true;
  22877. cb(clickInfo, _this._currentPickResult);
  22878. };
  22879. this._spritePredicate = function (sprite) {
  22880. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  22881. };
  22882. this._onPointerMove = function (evt) {
  22883. _this._updatePointerPosition(evt);
  22884. // PreObservable support
  22885. if (_this.onPrePointerObservable.hasObservers()) {
  22886. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  22887. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22888. _this.onPrePointerObservable.notifyObservers(pi, type);
  22889. if (pi.skipOnPointerObservable) {
  22890. return;
  22891. }
  22892. }
  22893. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22894. return;
  22895. }
  22896. if (!_this.pointerMovePredicate) {
  22897. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  22898. }
  22899. // Meshes
  22900. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  22901. _this._processPointerMove(pickResult, evt);
  22902. };
  22903. this._onPointerDown = function (evt) {
  22904. _this._totalPointersPressed++;
  22905. _this._pickedDownMesh = null;
  22906. _this._meshPickProceed = false;
  22907. _this._updatePointerPosition(evt);
  22908. if (_this.preventDefaultOnPointerDown && canvas) {
  22909. evt.preventDefault();
  22910. canvas.focus();
  22911. }
  22912. // PreObservable support
  22913. if (_this.onPrePointerObservable.hasObservers()) {
  22914. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  22915. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22916. _this.onPrePointerObservable.notifyObservers(pi, type);
  22917. if (pi.skipOnPointerObservable) {
  22918. return;
  22919. }
  22920. }
  22921. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  22922. return;
  22923. }
  22924. _this._startingPointerPosition.x = _this._pointerX;
  22925. _this._startingPointerPosition.y = _this._pointerY;
  22926. _this._startingPointerTime = new Date().getTime();
  22927. if (!_this.pointerDownPredicate) {
  22928. _this.pointerDownPredicate = function (mesh) {
  22929. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  22930. };
  22931. }
  22932. // Meshes
  22933. _this._pickedDownMesh = null;
  22934. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  22935. _this._processPointerDown(pickResult, evt);
  22936. // Sprites
  22937. _this._pickedDownSprite = null;
  22938. if (_this.spriteManagers.length > 0) {
  22939. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  22940. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  22941. if (pickResult.pickedSprite.actionManager) {
  22942. _this._pickedDownSprite = pickResult.pickedSprite;
  22943. switch (evt.button) {
  22944. case 0:
  22945. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22946. break;
  22947. case 1:
  22948. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22949. break;
  22950. case 2:
  22951. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22952. break;
  22953. }
  22954. if (pickResult.pickedSprite.actionManager) {
  22955. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  22956. }
  22957. }
  22958. }
  22959. }
  22960. };
  22961. this._onPointerUp = function (evt) {
  22962. if (_this._totalPointersPressed === 0) {
  22963. return; // So we need to test it the pointer down was pressed before.
  22964. }
  22965. _this._totalPointersPressed--;
  22966. _this._pickedUpMesh = null;
  22967. _this._meshPickProceed = false;
  22968. _this._updatePointerPosition(evt);
  22969. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  22970. // PreObservable support
  22971. if (_this.onPrePointerObservable.hasObservers()) {
  22972. if (!clickInfo.ignore) {
  22973. if (!clickInfo.hasSwiped) {
  22974. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  22975. var type = BABYLON.PointerEventTypes.POINTERTAP;
  22976. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22977. _this.onPrePointerObservable.notifyObservers(pi, type);
  22978. if (pi.skipOnPointerObservable) {
  22979. return;
  22980. }
  22981. }
  22982. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  22983. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  22984. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22985. _this.onPrePointerObservable.notifyObservers(pi, type);
  22986. if (pi.skipOnPointerObservable) {
  22987. return;
  22988. }
  22989. }
  22990. }
  22991. }
  22992. else {
  22993. var type = BABYLON.PointerEventTypes.POINTERUP;
  22994. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  22995. _this.onPrePointerObservable.notifyObservers(pi, type);
  22996. if (pi.skipOnPointerObservable) {
  22997. return;
  22998. }
  22999. }
  23000. }
  23001. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  23002. return;
  23003. }
  23004. if (!_this.pointerUpPredicate) {
  23005. _this.pointerUpPredicate = function (mesh) {
  23006. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  23007. };
  23008. }
  23009. // Meshes
  23010. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  23011. _this._initActionManager(null, clickInfo);
  23012. }
  23013. if (!pickResult) {
  23014. pickResult = _this._currentPickResult;
  23015. }
  23016. _this._processPointerUp(pickResult, evt, clickInfo);
  23017. // Sprites
  23018. if (_this.spriteManagers.length > 0) {
  23019. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  23020. if (spritePickResult) {
  23021. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  23022. if (spritePickResult.pickedSprite.actionManager) {
  23023. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  23024. if (spritePickResult.pickedSprite.actionManager) {
  23025. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  23026. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  23027. }
  23028. }
  23029. }
  23030. }
  23031. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  23032. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  23033. }
  23034. }
  23035. }
  23036. _this._previousPickResult = _this._currentPickResult;
  23037. });
  23038. };
  23039. this._onKeyDown = function (evt) {
  23040. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  23041. if (_this.onPreKeyboardObservable.hasObservers()) {
  23042. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  23043. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  23044. if (pi.skipOnPointerObservable) {
  23045. return;
  23046. }
  23047. }
  23048. if (_this.onKeyboardObservable.hasObservers()) {
  23049. var pi = new BABYLON.KeyboardInfo(type, evt);
  23050. _this.onKeyboardObservable.notifyObservers(pi, type);
  23051. }
  23052. if (_this.actionManager) {
  23053. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  23054. }
  23055. };
  23056. this._onKeyUp = function (evt) {
  23057. var type = BABYLON.KeyboardEventTypes.KEYUP;
  23058. if (_this.onPreKeyboardObservable.hasObservers()) {
  23059. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  23060. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  23061. if (pi.skipOnPointerObservable) {
  23062. return;
  23063. }
  23064. }
  23065. if (_this.onKeyboardObservable.hasObservers()) {
  23066. var pi = new BABYLON.KeyboardInfo(type, evt);
  23067. _this.onKeyboardObservable.notifyObservers(pi, type);
  23068. }
  23069. if (_this.actionManager) {
  23070. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  23071. }
  23072. };
  23073. var engine = this.getEngine();
  23074. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  23075. if (!canvas) {
  23076. return;
  23077. }
  23078. canvas.addEventListener("keydown", _this._onKeyDown, false);
  23079. canvas.addEventListener("keyup", _this._onKeyUp, false);
  23080. });
  23081. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  23082. if (!canvas) {
  23083. return;
  23084. }
  23085. canvas.removeEventListener("keydown", _this._onKeyDown);
  23086. canvas.removeEventListener("keyup", _this._onKeyUp);
  23087. });
  23088. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  23089. var canvas = this._engine.getRenderingCanvas();
  23090. if (!canvas) {
  23091. return;
  23092. }
  23093. if (attachMove) {
  23094. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  23095. // Wheel
  23096. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  23097. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  23098. }
  23099. if (attachDown) {
  23100. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  23101. }
  23102. if (attachUp) {
  23103. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  23104. }
  23105. canvas.tabIndex = 1;
  23106. };
  23107. Scene.prototype.detachControl = function () {
  23108. var engine = this.getEngine();
  23109. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  23110. var canvas = engine.getRenderingCanvas();
  23111. if (!canvas) {
  23112. return;
  23113. }
  23114. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  23115. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  23116. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  23117. if (this._onCanvasBlurObserver) {
  23118. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  23119. }
  23120. if (this._onCanvasFocusObserver) {
  23121. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  23122. }
  23123. // Wheel
  23124. canvas.removeEventListener('mousewheel', this._onPointerMove);
  23125. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  23126. // Keyboard
  23127. canvas.removeEventListener("keydown", this._onKeyDown);
  23128. canvas.removeEventListener("keyup", this._onKeyUp);
  23129. // Observables
  23130. this.onKeyboardObservable.clear();
  23131. this.onPreKeyboardObservable.clear();
  23132. this.onPointerObservable.clear();
  23133. this.onPrePointerObservable.clear();
  23134. };
  23135. /**
  23136. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  23137. * Delay loaded resources are not taking in account
  23138. * @return true if all required resources are ready
  23139. */
  23140. Scene.prototype.isReady = function () {
  23141. if (this._isDisposed) {
  23142. return false;
  23143. }
  23144. if (this._pendingData.length > 0) {
  23145. return false;
  23146. }
  23147. var index;
  23148. var engine = this.getEngine();
  23149. // Geometries
  23150. for (index = 0; index < this._geometries.length; index++) {
  23151. var geometry = this._geometries[index];
  23152. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  23153. return false;
  23154. }
  23155. }
  23156. // Meshes
  23157. for (index = 0; index < this.meshes.length; index++) {
  23158. var mesh = this.meshes[index];
  23159. if (!mesh.isEnabled()) {
  23160. continue;
  23161. }
  23162. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  23163. continue;
  23164. }
  23165. if (!mesh.isReady(true)) {
  23166. return false;
  23167. }
  23168. // Effect layers
  23169. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  23170. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  23171. var layer = _a[_i];
  23172. if (!layer.hasMesh(mesh)) {
  23173. continue;
  23174. }
  23175. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  23176. var subMesh = _c[_b];
  23177. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  23178. return false;
  23179. }
  23180. }
  23181. }
  23182. }
  23183. // Particles
  23184. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  23185. var particleSystem = _e[_d];
  23186. if (!particleSystem.isReady()) {
  23187. return false;
  23188. }
  23189. }
  23190. return true;
  23191. };
  23192. Scene.prototype.resetCachedMaterial = function () {
  23193. this._cachedMaterial = null;
  23194. this._cachedEffect = null;
  23195. this._cachedVisibility = null;
  23196. };
  23197. Scene.prototype.registerBeforeRender = function (func) {
  23198. this.onBeforeRenderObservable.add(func);
  23199. };
  23200. Scene.prototype.unregisterBeforeRender = function (func) {
  23201. this.onBeforeRenderObservable.removeCallback(func);
  23202. };
  23203. Scene.prototype.registerAfterRender = function (func) {
  23204. this.onAfterRenderObservable.add(func);
  23205. };
  23206. Scene.prototype.unregisterAfterRender = function (func) {
  23207. this.onAfterRenderObservable.removeCallback(func);
  23208. };
  23209. Scene.prototype._executeOnceBeforeRender = function (func) {
  23210. var _this = this;
  23211. var execFunc = function () {
  23212. func();
  23213. setTimeout(function () {
  23214. _this.unregisterBeforeRender(execFunc);
  23215. });
  23216. };
  23217. this.registerBeforeRender(execFunc);
  23218. };
  23219. /**
  23220. * The provided function will run before render once and will be disposed afterwards.
  23221. * A timeout delay can be provided so that the function will be executed in N ms.
  23222. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  23223. * @param func The function to be executed.
  23224. * @param timeout optional delay in ms
  23225. */
  23226. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  23227. var _this = this;
  23228. if (timeout !== undefined) {
  23229. setTimeout(function () {
  23230. _this._executeOnceBeforeRender(func);
  23231. }, timeout);
  23232. }
  23233. else {
  23234. this._executeOnceBeforeRender(func);
  23235. }
  23236. };
  23237. Scene.prototype._addPendingData = function (data) {
  23238. this._pendingData.push(data);
  23239. };
  23240. Scene.prototype._removePendingData = function (data) {
  23241. var wasLoading = this.isLoading;
  23242. var index = this._pendingData.indexOf(data);
  23243. if (index !== -1) {
  23244. this._pendingData.splice(index, 1);
  23245. }
  23246. if (wasLoading && !this.isLoading) {
  23247. this.onDataLoadedObservable.notifyObservers(this);
  23248. }
  23249. };
  23250. Scene.prototype.getWaitingItemsCount = function () {
  23251. return this._pendingData.length;
  23252. };
  23253. Object.defineProperty(Scene.prototype, "isLoading", {
  23254. get: function () {
  23255. return this._pendingData.length > 0;
  23256. },
  23257. enumerable: true,
  23258. configurable: true
  23259. });
  23260. /**
  23261. * Registers a function to be executed when the scene is ready.
  23262. * @param {Function} func - the function to be executed.
  23263. */
  23264. Scene.prototype.executeWhenReady = function (func) {
  23265. var _this = this;
  23266. this.onReadyObservable.add(func);
  23267. if (this._executeWhenReadyTimeoutId !== -1) {
  23268. return;
  23269. }
  23270. this._executeWhenReadyTimeoutId = setTimeout(function () {
  23271. _this._checkIsReady();
  23272. }, 150);
  23273. };
  23274. /**
  23275. * Returns a promise that resolves when the scene is ready.
  23276. * @returns A promise that resolves when the scene is ready.
  23277. */
  23278. Scene.prototype.whenReadyAsync = function () {
  23279. var _this = this;
  23280. return new Promise(function (resolve) {
  23281. _this.executeWhenReady(function () {
  23282. resolve();
  23283. });
  23284. });
  23285. };
  23286. Scene.prototype._checkIsReady = function () {
  23287. var _this = this;
  23288. if (this.isReady()) {
  23289. this.onReadyObservable.notifyObservers(this);
  23290. this.onReadyObservable.clear();
  23291. this._executeWhenReadyTimeoutId = -1;
  23292. return;
  23293. }
  23294. this._executeWhenReadyTimeoutId = setTimeout(function () {
  23295. _this._checkIsReady();
  23296. }, 150);
  23297. };
  23298. // Animations
  23299. /**
  23300. * Will start the animation sequence of a given target
  23301. * @param target defines the target
  23302. * @param from defines from which frame should animation start
  23303. * @param to defines until which frame should animation run.
  23304. * @param weight defines the weight to apply to the animation (1.0 by default)
  23305. * @param loop defines if the animation loops
  23306. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  23307. * @param onAnimationEnd defines the function to be executed when the animation ends
  23308. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  23309. * @returns the animatable object created for this animation
  23310. * @see BABYLON.Animatable
  23311. */
  23312. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  23313. if (weight === void 0) { weight = 1.0; }
  23314. if (speedRatio === void 0) { speedRatio = 1.0; }
  23315. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  23316. returnedAnimatable.weight = weight;
  23317. return returnedAnimatable;
  23318. };
  23319. /**
  23320. * Will start the animation sequence of a given target
  23321. * @param target defines the target
  23322. * @param from defines from which frame should animation start
  23323. * @param to defines until which frame should animation run.
  23324. * @param loop defines if the animation loops
  23325. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  23326. * @param onAnimationEnd defines the function to be executed when the animation ends
  23327. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  23328. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  23329. * @returns the animatable object created for this animation
  23330. * @see BABYLON.Animatable
  23331. */
  23332. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  23333. if (speedRatio === void 0) { speedRatio = 1.0; }
  23334. if (stopCurrent === void 0) { stopCurrent = true; }
  23335. if (from > to && speedRatio > 0) {
  23336. speedRatio *= -1;
  23337. }
  23338. if (stopCurrent) {
  23339. this.stopAnimation(target);
  23340. }
  23341. if (!animatable) {
  23342. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  23343. }
  23344. // Local animations
  23345. if (target.animations) {
  23346. animatable.appendAnimations(target, target.animations);
  23347. }
  23348. // Children animations
  23349. if (target.getAnimatables) {
  23350. var animatables = target.getAnimatables();
  23351. for (var index = 0; index < animatables.length; index++) {
  23352. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  23353. }
  23354. }
  23355. if (stopCurrent) {
  23356. animatable.reset();
  23357. }
  23358. return animatable;
  23359. };
  23360. /**
  23361. * Begin a new animation on a given node
  23362. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23363. * @param {BABYLON.Animation[]} defines the list of animations to start
  23364. * @param {number} from defines the initial value
  23365. * @param {number} to defines the final value
  23366. * @param {boolean} loop defines if you want animation to loop (off by default)
  23367. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23368. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23369. * @returns the list of created animatables
  23370. */
  23371. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23372. if (speedRatio === undefined) {
  23373. speedRatio = 1.0;
  23374. }
  23375. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  23376. return animatable;
  23377. };
  23378. /**
  23379. * Begin a new animation on a given node and its hierarchy
  23380. * @param {BABYLON.Node} node defines the root node where the animation will take place
  23381. * @param {boolean} directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used.
  23382. * @param {BABYLON.Animation[]} defines the list of animations to start
  23383. * @param {number} from defines the initial value
  23384. * @param {number} to defines the final value
  23385. * @param {boolean} loop defines if you want animation to loop (off by default)
  23386. * @param {number} speedRatio defines the speed ratio to apply to all animations
  23387. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  23388. * @returns the list of animatables created for all nodes
  23389. */
  23390. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  23391. var children = target.getDescendants(directDescendantsOnly);
  23392. var result = [];
  23393. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  23394. var child = children_1[_i];
  23395. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  23396. }
  23397. return result;
  23398. };
  23399. Scene.prototype.getAnimatableByTarget = function (target) {
  23400. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23401. if (this._activeAnimatables[index].target === target) {
  23402. return this._activeAnimatables[index];
  23403. }
  23404. }
  23405. return null;
  23406. };
  23407. Object.defineProperty(Scene.prototype, "animatables", {
  23408. get: function () {
  23409. return this._activeAnimatables;
  23410. },
  23411. enumerable: true,
  23412. configurable: true
  23413. });
  23414. /**
  23415. * Will stop the animation of the given target
  23416. * @param target - the target
  23417. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  23418. * @see beginAnimation
  23419. */
  23420. Scene.prototype.stopAnimation = function (target, animationName) {
  23421. var animatable = this.getAnimatableByTarget(target);
  23422. if (animatable) {
  23423. animatable.stop(animationName);
  23424. }
  23425. };
  23426. /**
  23427. * Stops and removes all animations that have been applied to the scene
  23428. */
  23429. Scene.prototype.stopAllAnimations = function () {
  23430. if (this._activeAnimatables) {
  23431. for (var i = 0; i < this._activeAnimatables.length; i++) {
  23432. this._activeAnimatables[i].stop();
  23433. }
  23434. this._activeAnimatables = [];
  23435. }
  23436. };
  23437. Scene.prototype._animate = function () {
  23438. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  23439. return;
  23440. }
  23441. // Getting time
  23442. var now = BABYLON.Tools.Now;
  23443. if (!this._animationTimeLast) {
  23444. if (this._pendingData.length > 0) {
  23445. return;
  23446. }
  23447. this._animationTimeLast = now;
  23448. }
  23449. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  23450. this._animationTime += deltaTime;
  23451. this._animationTimeLast = now;
  23452. for (var index = 0; index < this._activeAnimatables.length; index++) {
  23453. this._activeAnimatables[index]._animate(this._animationTime);
  23454. }
  23455. // Late animation bindings
  23456. this._processLateAnimationBindings();
  23457. };
  23458. /** @ignore */
  23459. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation) {
  23460. var target = runtimeAnimation.target;
  23461. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  23462. if (!target._lateAnimationHolders) {
  23463. target._lateAnimationHolders = {};
  23464. }
  23465. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  23466. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  23467. totalWeight: 0,
  23468. animations: []
  23469. };
  23470. }
  23471. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  23472. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  23473. };
  23474. Scene.prototype._processLateAnimationBindings = function () {
  23475. if (!this._registeredForLateAnimationBindings.length) {
  23476. return;
  23477. }
  23478. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  23479. var target = this._registeredForLateAnimationBindings.data[index];
  23480. for (var path in target._lateAnimationHolders) {
  23481. var holder = target._lateAnimationHolders[path];
  23482. // Sanity check
  23483. if (!holder.animations[0].originalValue.scaleAndAddToRef) {
  23484. continue;
  23485. }
  23486. var normalizer = 1.0;
  23487. var finalValue = void 0;
  23488. if (holder.totalWeight < 1.0) {
  23489. // We need to mix the original value in
  23490. var originalValue = holder.animations[0].originalValue;
  23491. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  23492. }
  23493. else {
  23494. // We need to normalize the weights
  23495. normalizer = holder.totalWeight;
  23496. }
  23497. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  23498. var runtimeAnimation = holder.animations[animIndex];
  23499. if (finalValue) {
  23500. runtimeAnimation.currentValue.scaleAndAddToRef(runtimeAnimation.weight / normalizer, finalValue);
  23501. }
  23502. else {
  23503. finalValue = runtimeAnimation.currentValue.scale(runtimeAnimation.weight / normalizer);
  23504. }
  23505. }
  23506. runtimeAnimation.target[path] = finalValue;
  23507. }
  23508. target._lateAnimationHolders = {};
  23509. }
  23510. this._registeredForLateAnimationBindings.reset();
  23511. };
  23512. // Matrix
  23513. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  23514. this._useAlternateCameraConfiguration = active;
  23515. };
  23516. Scene.prototype.getViewMatrix = function () {
  23517. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  23518. };
  23519. Scene.prototype.getProjectionMatrix = function () {
  23520. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  23521. };
  23522. Scene.prototype.getTransformMatrix = function () {
  23523. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  23524. };
  23525. Scene.prototype.setTransformMatrix = function (view, projection) {
  23526. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  23527. return;
  23528. }
  23529. this._viewUpdateFlag = view.updateFlag;
  23530. this._projectionUpdateFlag = projection.updateFlag;
  23531. this._viewMatrix = view;
  23532. this._projectionMatrix = projection;
  23533. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  23534. // Update frustum
  23535. if (!this._frustumPlanes) {
  23536. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  23537. }
  23538. else {
  23539. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  23540. }
  23541. if (this.activeCamera && this.activeCamera._alternateCamera) {
  23542. var otherCamera = this.activeCamera._alternateCamera;
  23543. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  23544. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  23545. }
  23546. if (this._sceneUbo.useUbo) {
  23547. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  23548. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  23549. this._sceneUbo.update();
  23550. }
  23551. };
  23552. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  23553. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  23554. return;
  23555. }
  23556. this._alternateViewUpdateFlag = view.updateFlag;
  23557. this._alternateProjectionUpdateFlag = projection.updateFlag;
  23558. this._alternateViewMatrix = view;
  23559. this._alternateProjectionMatrix = projection;
  23560. if (!this._alternateTransformMatrix) {
  23561. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  23562. }
  23563. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  23564. if (!this._alternateSceneUbo) {
  23565. this._createAlternateUbo();
  23566. }
  23567. if (this._alternateSceneUbo.useUbo) {
  23568. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  23569. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  23570. this._alternateSceneUbo.update();
  23571. }
  23572. };
  23573. Scene.prototype.getSceneUniformBuffer = function () {
  23574. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  23575. };
  23576. // Methods
  23577. Scene.prototype.getUniqueId = function () {
  23578. var result = Scene._uniqueIdCounter;
  23579. Scene._uniqueIdCounter++;
  23580. return result;
  23581. };
  23582. Scene.prototype.addMesh = function (newMesh) {
  23583. this.meshes.push(newMesh);
  23584. //notify the collision coordinator
  23585. if (this.collisionCoordinator) {
  23586. this.collisionCoordinator.onMeshAdded(newMesh);
  23587. }
  23588. newMesh._resyncLightSources();
  23589. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  23590. };
  23591. Scene.prototype.removeMesh = function (toRemove) {
  23592. var index = this.meshes.indexOf(toRemove);
  23593. if (index !== -1) {
  23594. // Remove from the scene if mesh found
  23595. this.meshes.splice(index, 1);
  23596. }
  23597. this.onMeshRemovedObservable.notifyObservers(toRemove);
  23598. return index;
  23599. };
  23600. Scene.prototype.addTransformNode = function (newTransformNode) {
  23601. this.transformNodes.push(newTransformNode);
  23602. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  23603. };
  23604. Scene.prototype.removeTransformNode = function (toRemove) {
  23605. var index = this.transformNodes.indexOf(toRemove);
  23606. if (index !== -1) {
  23607. // Remove from the scene if found
  23608. this.transformNodes.splice(index, 1);
  23609. }
  23610. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  23611. return index;
  23612. };
  23613. Scene.prototype.removeSkeleton = function (toRemove) {
  23614. var index = this.skeletons.indexOf(toRemove);
  23615. if (index !== -1) {
  23616. // Remove from the scene if found
  23617. this.skeletons.splice(index, 1);
  23618. }
  23619. return index;
  23620. };
  23621. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  23622. var index = this.morphTargetManagers.indexOf(toRemove);
  23623. if (index !== -1) {
  23624. // Remove from the scene if found
  23625. this.morphTargetManagers.splice(index, 1);
  23626. }
  23627. return index;
  23628. };
  23629. Scene.prototype.removeLight = function (toRemove) {
  23630. var index = this.lights.indexOf(toRemove);
  23631. if (index !== -1) {
  23632. // Remove from meshes
  23633. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23634. var mesh = _a[_i];
  23635. mesh._removeLightSource(toRemove);
  23636. }
  23637. // Remove from the scene if mesh found
  23638. this.lights.splice(index, 1);
  23639. this.sortLightsByPriority();
  23640. }
  23641. this.onLightRemovedObservable.notifyObservers(toRemove);
  23642. return index;
  23643. };
  23644. Scene.prototype.removeCamera = function (toRemove) {
  23645. var index = this.cameras.indexOf(toRemove);
  23646. if (index !== -1) {
  23647. // Remove from the scene if mesh found
  23648. this.cameras.splice(index, 1);
  23649. }
  23650. // Remove from activeCameras
  23651. var index2 = this.activeCameras.indexOf(toRemove);
  23652. if (index2 !== -1) {
  23653. // Remove from the scene if mesh found
  23654. this.activeCameras.splice(index2, 1);
  23655. }
  23656. // Reset the activeCamera
  23657. if (this.activeCamera === toRemove) {
  23658. if (this.cameras.length > 0) {
  23659. this.activeCamera = this.cameras[0];
  23660. }
  23661. else {
  23662. this.activeCamera = null;
  23663. }
  23664. }
  23665. this.onCameraRemovedObservable.notifyObservers(toRemove);
  23666. return index;
  23667. };
  23668. Scene.prototype.removeParticleSystem = function (toRemove) {
  23669. var index = this.particleSystems.indexOf(toRemove);
  23670. if (index !== -1) {
  23671. this.particleSystems.splice(index, 1);
  23672. }
  23673. return index;
  23674. };
  23675. ;
  23676. Scene.prototype.removeAnimation = function (toRemove) {
  23677. var index = this.animations.indexOf(toRemove);
  23678. if (index !== -1) {
  23679. this.animations.splice(index, 1);
  23680. }
  23681. return index;
  23682. };
  23683. ;
  23684. Scene.prototype.removeMultiMaterial = function (toRemove) {
  23685. var index = this.multiMaterials.indexOf(toRemove);
  23686. if (index !== -1) {
  23687. this.multiMaterials.splice(index, 1);
  23688. }
  23689. return index;
  23690. };
  23691. ;
  23692. Scene.prototype.removeMaterial = function (toRemove) {
  23693. var index = this.materials.indexOf(toRemove);
  23694. if (index !== -1) {
  23695. this.materials.splice(index, 1);
  23696. }
  23697. return index;
  23698. };
  23699. ;
  23700. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  23701. var index = this.lensFlareSystems.indexOf(toRemove);
  23702. if (index !== -1) {
  23703. this.lensFlareSystems.splice(index, 1);
  23704. }
  23705. return index;
  23706. };
  23707. ;
  23708. Scene.prototype.removeActionManager = function (toRemove) {
  23709. var index = this._actionManagers.indexOf(toRemove);
  23710. if (index !== -1) {
  23711. this._actionManagers.splice(index, 1);
  23712. }
  23713. return index;
  23714. };
  23715. ;
  23716. Scene.prototype.addLight = function (newLight) {
  23717. this.lights.push(newLight);
  23718. this.sortLightsByPriority();
  23719. // Add light to all meshes (To support if the light is removed and then readded)
  23720. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  23721. var mesh = _a[_i];
  23722. if (mesh._lightSources.indexOf(newLight) === -1) {
  23723. mesh._lightSources.push(newLight);
  23724. mesh._resyncLightSources();
  23725. }
  23726. }
  23727. this.onNewLightAddedObservable.notifyObservers(newLight);
  23728. };
  23729. Scene.prototype.sortLightsByPriority = function () {
  23730. if (this.requireLightSorting) {
  23731. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  23732. }
  23733. };
  23734. Scene.prototype.addCamera = function (newCamera) {
  23735. this.cameras.push(newCamera);
  23736. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  23737. };
  23738. Scene.prototype.addSkeleton = function (newSkeleton) {
  23739. this.skeletons.push(newSkeleton);
  23740. };
  23741. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  23742. this.particleSystems.push(newParticleSystem);
  23743. };
  23744. Scene.prototype.addAnimation = function (newAnimation) {
  23745. this.animations.push(newAnimation);
  23746. };
  23747. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  23748. this.multiMaterials.push(newMultiMaterial);
  23749. };
  23750. Scene.prototype.addMaterial = function (newMaterial) {
  23751. this.materials.push(newMaterial);
  23752. };
  23753. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  23754. this.morphTargetManagers.push(newMorphTargetManager);
  23755. };
  23756. Scene.prototype.addGeometry = function (newGeometrie) {
  23757. this._geometries.push(newGeometrie);
  23758. };
  23759. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  23760. this.lensFlareSystems.push(newLensFlareSystem);
  23761. };
  23762. Scene.prototype.addActionManager = function (newActionManager) {
  23763. this._actionManagers.push(newActionManager);
  23764. };
  23765. /**
  23766. * Switch active camera
  23767. * @param {Camera} newCamera - new active camera
  23768. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  23769. */
  23770. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  23771. if (attachControl === void 0) { attachControl = true; }
  23772. var canvas = this._engine.getRenderingCanvas();
  23773. if (!canvas) {
  23774. return;
  23775. }
  23776. if (this.activeCamera) {
  23777. this.activeCamera.detachControl(canvas);
  23778. }
  23779. this.activeCamera = newCamera;
  23780. if (attachControl) {
  23781. newCamera.attachControl(canvas);
  23782. }
  23783. };
  23784. /**
  23785. * sets the active camera of the scene using its ID
  23786. * @param {string} id - the camera's ID
  23787. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23788. * @see activeCamera
  23789. */
  23790. Scene.prototype.setActiveCameraByID = function (id) {
  23791. var camera = this.getCameraByID(id);
  23792. if (camera) {
  23793. this.activeCamera = camera;
  23794. return camera;
  23795. }
  23796. return null;
  23797. };
  23798. /**
  23799. * sets the active camera of the scene using its name
  23800. * @param {string} name - the camera's name
  23801. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  23802. * @see activeCamera
  23803. */
  23804. Scene.prototype.setActiveCameraByName = function (name) {
  23805. var camera = this.getCameraByName(name);
  23806. if (camera) {
  23807. this.activeCamera = camera;
  23808. return camera;
  23809. }
  23810. return null;
  23811. };
  23812. /**
  23813. * get an animation group using its name
  23814. * @param {string} the material's name
  23815. * @return {BABYLON.AnimationGroup|null} the animation group or null if none found.
  23816. */
  23817. Scene.prototype.getAnimationGroupByName = function (name) {
  23818. for (var index = 0; index < this.animationGroups.length; index++) {
  23819. if (this.animationGroups[index].name === name) {
  23820. return this.animationGroups[index];
  23821. }
  23822. }
  23823. return null;
  23824. };
  23825. /**
  23826. * get a material using its id
  23827. * @param {string} the material's ID
  23828. * @return {BABYLON.Material|null} the material or null if none found.
  23829. */
  23830. Scene.prototype.getMaterialByID = function (id) {
  23831. for (var index = 0; index < this.materials.length; index++) {
  23832. if (this.materials[index].id === id) {
  23833. return this.materials[index];
  23834. }
  23835. }
  23836. return null;
  23837. };
  23838. /**
  23839. * get a material using its name
  23840. * @param {string} the material's name
  23841. * @return {BABYLON.Material|null} the material or null if none found.
  23842. */
  23843. Scene.prototype.getMaterialByName = function (name) {
  23844. for (var index = 0; index < this.materials.length; index++) {
  23845. if (this.materials[index].name === name) {
  23846. return this.materials[index];
  23847. }
  23848. }
  23849. return null;
  23850. };
  23851. Scene.prototype.getLensFlareSystemByName = function (name) {
  23852. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23853. if (this.lensFlareSystems[index].name === name) {
  23854. return this.lensFlareSystems[index];
  23855. }
  23856. }
  23857. return null;
  23858. };
  23859. Scene.prototype.getLensFlareSystemByID = function (id) {
  23860. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  23861. if (this.lensFlareSystems[index].id === id) {
  23862. return this.lensFlareSystems[index];
  23863. }
  23864. }
  23865. return null;
  23866. };
  23867. Scene.prototype.getCameraByID = function (id) {
  23868. for (var index = 0; index < this.cameras.length; index++) {
  23869. if (this.cameras[index].id === id) {
  23870. return this.cameras[index];
  23871. }
  23872. }
  23873. return null;
  23874. };
  23875. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  23876. for (var index = 0; index < this.cameras.length; index++) {
  23877. if (this.cameras[index].uniqueId === uniqueId) {
  23878. return this.cameras[index];
  23879. }
  23880. }
  23881. return null;
  23882. };
  23883. /**
  23884. * get a camera using its name
  23885. * @param {string} the camera's name
  23886. * @return {BABYLON.Camera|null} the camera or null if none found.
  23887. */
  23888. Scene.prototype.getCameraByName = function (name) {
  23889. for (var index = 0; index < this.cameras.length; index++) {
  23890. if (this.cameras[index].name === name) {
  23891. return this.cameras[index];
  23892. }
  23893. }
  23894. return null;
  23895. };
  23896. /**
  23897. * get a bone using its id
  23898. * @param {string} the bone's id
  23899. * @return {BABYLON.Bone|null} the bone or null if not found
  23900. */
  23901. Scene.prototype.getBoneByID = function (id) {
  23902. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23903. var skeleton = this.skeletons[skeletonIndex];
  23904. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23905. if (skeleton.bones[boneIndex].id === id) {
  23906. return skeleton.bones[boneIndex];
  23907. }
  23908. }
  23909. }
  23910. return null;
  23911. };
  23912. /**
  23913. * get a bone using its id
  23914. * @param {string} the bone's name
  23915. * @return {BABYLON.Bone|null} the bone or null if not found
  23916. */
  23917. Scene.prototype.getBoneByName = function (name) {
  23918. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  23919. var skeleton = this.skeletons[skeletonIndex];
  23920. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  23921. if (skeleton.bones[boneIndex].name === name) {
  23922. return skeleton.bones[boneIndex];
  23923. }
  23924. }
  23925. }
  23926. return null;
  23927. };
  23928. /**
  23929. * get a light node using its name
  23930. * @param {string} the light's name
  23931. * @return {BABYLON.Light|null} the light or null if none found.
  23932. */
  23933. Scene.prototype.getLightByName = function (name) {
  23934. for (var index = 0; index < this.lights.length; index++) {
  23935. if (this.lights[index].name === name) {
  23936. return this.lights[index];
  23937. }
  23938. }
  23939. return null;
  23940. };
  23941. /**
  23942. * get a light node using its ID
  23943. * @param {string} the light's id
  23944. * @return {BABYLON.Light|null} the light or null if none found.
  23945. */
  23946. Scene.prototype.getLightByID = function (id) {
  23947. for (var index = 0; index < this.lights.length; index++) {
  23948. if (this.lights[index].id === id) {
  23949. return this.lights[index];
  23950. }
  23951. }
  23952. return null;
  23953. };
  23954. /**
  23955. * get a light node using its scene-generated unique ID
  23956. * @param {number} the light's unique id
  23957. * @return {BABYLON.Light|null} the light or null if none found.
  23958. */
  23959. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  23960. for (var index = 0; index < this.lights.length; index++) {
  23961. if (this.lights[index].uniqueId === uniqueId) {
  23962. return this.lights[index];
  23963. }
  23964. }
  23965. return null;
  23966. };
  23967. /**
  23968. * get a particle system by id
  23969. * @param id {number} the particle system id
  23970. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  23971. */
  23972. Scene.prototype.getParticleSystemByID = function (id) {
  23973. for (var index = 0; index < this.particleSystems.length; index++) {
  23974. if (this.particleSystems[index].id === id) {
  23975. return this.particleSystems[index];
  23976. }
  23977. }
  23978. return null;
  23979. };
  23980. /**
  23981. * get a geometry using its ID
  23982. * @param {string} the geometry's id
  23983. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  23984. */
  23985. Scene.prototype.getGeometryByID = function (id) {
  23986. for (var index = 0; index < this._geometries.length; index++) {
  23987. if (this._geometries[index].id === id) {
  23988. return this._geometries[index];
  23989. }
  23990. }
  23991. return null;
  23992. };
  23993. /**
  23994. * add a new geometry to this scene.
  23995. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  23996. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  23997. * @return {boolean} was the geometry added or not
  23998. */
  23999. Scene.prototype.pushGeometry = function (geometry, force) {
  24000. if (!force && this.getGeometryByID(geometry.id)) {
  24001. return false;
  24002. }
  24003. this._geometries.push(geometry);
  24004. //notify the collision coordinator
  24005. if (this.collisionCoordinator) {
  24006. this.collisionCoordinator.onGeometryAdded(geometry);
  24007. }
  24008. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  24009. return true;
  24010. };
  24011. /**
  24012. * Removes an existing geometry
  24013. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  24014. * @return {boolean} was the geometry removed or not
  24015. */
  24016. Scene.prototype.removeGeometry = function (geometry) {
  24017. var index = this._geometries.indexOf(geometry);
  24018. if (index > -1) {
  24019. this._geometries.splice(index, 1);
  24020. //notify the collision coordinator
  24021. if (this.collisionCoordinator) {
  24022. this.collisionCoordinator.onGeometryDeleted(geometry);
  24023. }
  24024. this.onGeometryRemovedObservable.notifyObservers(geometry);
  24025. return true;
  24026. }
  24027. return false;
  24028. };
  24029. Scene.prototype.getGeometries = function () {
  24030. return this._geometries;
  24031. };
  24032. /**
  24033. * Get the first added mesh found of a given ID
  24034. * @param {string} id - the id to search for
  24035. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  24036. */
  24037. Scene.prototype.getMeshByID = function (id) {
  24038. for (var index = 0; index < this.meshes.length; index++) {
  24039. if (this.meshes[index].id === id) {
  24040. return this.meshes[index];
  24041. }
  24042. }
  24043. return null;
  24044. };
  24045. Scene.prototype.getMeshesByID = function (id) {
  24046. return this.meshes.filter(function (m) {
  24047. return m.id === id;
  24048. });
  24049. };
  24050. /**
  24051. * Get the first added transform node found of a given ID
  24052. * @param {string} id - the id to search for
  24053. * @return {BABYLON.TransformNode|null} the transform node found or null if not found at all.
  24054. */
  24055. Scene.prototype.getTransformNodeByID = function (id) {
  24056. for (var index = 0; index < this.transformNodes.length; index++) {
  24057. if (this.transformNodes[index].id === id) {
  24058. return this.transformNodes[index];
  24059. }
  24060. }
  24061. return null;
  24062. };
  24063. Scene.prototype.getTransformNodesByID = function (id) {
  24064. return this.transformNodes.filter(function (m) {
  24065. return m.id === id;
  24066. });
  24067. };
  24068. /**
  24069. * Get a mesh with its auto-generated unique id
  24070. * @param {number} uniqueId - the unique id to search for
  24071. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  24072. */
  24073. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  24074. for (var index = 0; index < this.meshes.length; index++) {
  24075. if (this.meshes[index].uniqueId === uniqueId) {
  24076. return this.meshes[index];
  24077. }
  24078. }
  24079. return null;
  24080. };
  24081. /**
  24082. * Get a the last added mesh found of a given ID
  24083. * @param {string} id - the id to search for
  24084. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  24085. */
  24086. Scene.prototype.getLastMeshByID = function (id) {
  24087. for (var index = this.meshes.length - 1; index >= 0; index--) {
  24088. if (this.meshes[index].id === id) {
  24089. return this.meshes[index];
  24090. }
  24091. }
  24092. return null;
  24093. };
  24094. /**
  24095. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  24096. * @param {string} id - the id to search for
  24097. * @return {BABYLON.Node|null} the node found or null if not found at all.
  24098. */
  24099. Scene.prototype.getLastEntryByID = function (id) {
  24100. var index;
  24101. for (index = this.meshes.length - 1; index >= 0; index--) {
  24102. if (this.meshes[index].id === id) {
  24103. return this.meshes[index];
  24104. }
  24105. }
  24106. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  24107. if (this.transformNodes[index].id === id) {
  24108. return this.transformNodes[index];
  24109. }
  24110. }
  24111. for (index = this.cameras.length - 1; index >= 0; index--) {
  24112. if (this.cameras[index].id === id) {
  24113. return this.cameras[index];
  24114. }
  24115. }
  24116. for (index = this.lights.length - 1; index >= 0; index--) {
  24117. if (this.lights[index].id === id) {
  24118. return this.lights[index];
  24119. }
  24120. }
  24121. return null;
  24122. };
  24123. Scene.prototype.getNodeByID = function (id) {
  24124. var mesh = this.getMeshByID(id);
  24125. if (mesh) {
  24126. return mesh;
  24127. }
  24128. var light = this.getLightByID(id);
  24129. if (light) {
  24130. return light;
  24131. }
  24132. var camera = this.getCameraByID(id);
  24133. if (camera) {
  24134. return camera;
  24135. }
  24136. var bone = this.getBoneByID(id);
  24137. return bone;
  24138. };
  24139. Scene.prototype.getNodeByName = function (name) {
  24140. var mesh = this.getMeshByName(name);
  24141. if (mesh) {
  24142. return mesh;
  24143. }
  24144. var light = this.getLightByName(name);
  24145. if (light) {
  24146. return light;
  24147. }
  24148. var camera = this.getCameraByName(name);
  24149. if (camera) {
  24150. return camera;
  24151. }
  24152. var bone = this.getBoneByName(name);
  24153. return bone;
  24154. };
  24155. Scene.prototype.getMeshByName = function (name) {
  24156. for (var index = 0; index < this.meshes.length; index++) {
  24157. if (this.meshes[index].name === name) {
  24158. return this.meshes[index];
  24159. }
  24160. }
  24161. return null;
  24162. };
  24163. Scene.prototype.getTransformNodeByName = function (name) {
  24164. for (var index = 0; index < this.transformNodes.length; index++) {
  24165. if (this.transformNodes[index].name === name) {
  24166. return this.transformNodes[index];
  24167. }
  24168. }
  24169. return null;
  24170. };
  24171. Scene.prototype.getSoundByName = function (name) {
  24172. var index;
  24173. if (BABYLON.AudioEngine) {
  24174. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  24175. if (this.mainSoundTrack.soundCollection[index].name === name) {
  24176. return this.mainSoundTrack.soundCollection[index];
  24177. }
  24178. }
  24179. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  24180. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  24181. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  24182. return this.soundTracks[sdIndex].soundCollection[index];
  24183. }
  24184. }
  24185. }
  24186. }
  24187. return null;
  24188. };
  24189. Scene.prototype.getLastSkeletonByID = function (id) {
  24190. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  24191. if (this.skeletons[index].id === id) {
  24192. return this.skeletons[index];
  24193. }
  24194. }
  24195. return null;
  24196. };
  24197. Scene.prototype.getSkeletonById = function (id) {
  24198. for (var index = 0; index < this.skeletons.length; index++) {
  24199. if (this.skeletons[index].id === id) {
  24200. return this.skeletons[index];
  24201. }
  24202. }
  24203. return null;
  24204. };
  24205. Scene.prototype.getSkeletonByName = function (name) {
  24206. for (var index = 0; index < this.skeletons.length; index++) {
  24207. if (this.skeletons[index].name === name) {
  24208. return this.skeletons[index];
  24209. }
  24210. }
  24211. return null;
  24212. };
  24213. Scene.prototype.getMorphTargetManagerById = function (id) {
  24214. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  24215. if (this.morphTargetManagers[index].uniqueId === id) {
  24216. return this.morphTargetManagers[index];
  24217. }
  24218. }
  24219. return null;
  24220. };
  24221. Scene.prototype.isActiveMesh = function (mesh) {
  24222. return (this._activeMeshes.indexOf(mesh) !== -1);
  24223. };
  24224. /**
  24225. * Return a the first highlight layer of the scene with a given name.
  24226. * @param name The name of the highlight layer to look for.
  24227. * @return The highlight layer if found otherwise null.
  24228. */
  24229. Scene.prototype.getHighlightLayerByName = function (name) {
  24230. for (var index = 0; index < this.effectLayers.length; index++) {
  24231. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  24232. return this.effectLayers[index];
  24233. }
  24234. }
  24235. return null;
  24236. };
  24237. /**
  24238. * Return a the first highlight layer of the scene with a given name.
  24239. * @param name The name of the highlight layer to look for.
  24240. * @return The highlight layer if found otherwise null.
  24241. */
  24242. Scene.prototype.getGlowLayerByName = function (name) {
  24243. for (var index = 0; index < this.effectLayers.length; index++) {
  24244. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  24245. return this.effectLayers[index];
  24246. }
  24247. }
  24248. return null;
  24249. };
  24250. Object.defineProperty(Scene.prototype, "uid", {
  24251. /**
  24252. * Return a unique id as a string which can serve as an identifier for the scene
  24253. */
  24254. get: function () {
  24255. if (!this._uid) {
  24256. this._uid = BABYLON.Tools.RandomId();
  24257. }
  24258. return this._uid;
  24259. },
  24260. enumerable: true,
  24261. configurable: true
  24262. });
  24263. /**
  24264. * Add an externaly attached data from its key.
  24265. * This method call will fail and return false, if such key already exists.
  24266. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  24267. * @param key the unique key that identifies the data
  24268. * @param data the data object to associate to the key for this Engine instance
  24269. * @return true if no such key were already present and the data was added successfully, false otherwise
  24270. */
  24271. Scene.prototype.addExternalData = function (key, data) {
  24272. if (!this._externalData) {
  24273. this._externalData = new BABYLON.StringDictionary();
  24274. }
  24275. return this._externalData.add(key, data);
  24276. };
  24277. /**
  24278. * Get an externaly attached data from its key
  24279. * @param key the unique key that identifies the data
  24280. * @return the associated data, if present (can be null), or undefined if not present
  24281. */
  24282. Scene.prototype.getExternalData = function (key) {
  24283. if (!this._externalData) {
  24284. return null;
  24285. }
  24286. return this._externalData.get(key);
  24287. };
  24288. /**
  24289. * Get an externaly attached data from its key, create it using a factory if it's not already present
  24290. * @param key the unique key that identifies the data
  24291. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  24292. * @return the associated data, can be null if the factory returned null.
  24293. */
  24294. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  24295. if (!this._externalData) {
  24296. this._externalData = new BABYLON.StringDictionary();
  24297. }
  24298. return this._externalData.getOrAddWithFactory(key, factory);
  24299. };
  24300. /**
  24301. * Remove an externaly attached data from the Engine instance
  24302. * @param key the unique key that identifies the data
  24303. * @return true if the data was successfully removed, false if it doesn't exist
  24304. */
  24305. Scene.prototype.removeExternalData = function (key) {
  24306. return this._externalData.remove(key);
  24307. };
  24308. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  24309. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  24310. if (mesh.showSubMeshesBoundingBox) {
  24311. var boundingInfo = subMesh.getBoundingInfo();
  24312. if (boundingInfo !== null && boundingInfo !== undefined) {
  24313. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  24314. }
  24315. }
  24316. var material = subMesh.getMaterial();
  24317. if (material !== null && material !== undefined) {
  24318. // Render targets
  24319. if (material.getRenderTargetTextures !== undefined) {
  24320. if (this._processedMaterials.indexOf(material) === -1) {
  24321. this._processedMaterials.push(material);
  24322. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  24323. }
  24324. }
  24325. // Dispatch
  24326. this._activeIndices.addCount(subMesh.indexCount, false);
  24327. this._renderingManager.dispatch(subMesh, mesh, material);
  24328. }
  24329. }
  24330. };
  24331. /**
  24332. * Clear the processed materials smart array preventing retention point in material dispose.
  24333. */
  24334. Scene.prototype.freeProcessedMaterials = function () {
  24335. this._processedMaterials.dispose();
  24336. };
  24337. /**
  24338. * Clear the active meshes smart array preventing retention point in mesh dispose.
  24339. */
  24340. Scene.prototype.freeActiveMeshes = function () {
  24341. this._activeMeshes.dispose();
  24342. if (this.activeCamera && this.activeCamera._activeMeshes) {
  24343. this.activeCamera._activeMeshes.dispose();
  24344. }
  24345. if (this.activeCameras) {
  24346. for (var i = 0; i < this.activeCameras.length; i++) {
  24347. var activeCamera = this.activeCameras[i];
  24348. if (activeCamera && activeCamera._activeMeshes) {
  24349. activeCamera._activeMeshes.dispose();
  24350. }
  24351. }
  24352. }
  24353. };
  24354. /**
  24355. * Clear the info related to rendering groups preventing retention points during dispose.
  24356. */
  24357. Scene.prototype.freeRenderingGroups = function () {
  24358. if (this._renderingManager) {
  24359. this._renderingManager.freeRenderingGroups();
  24360. }
  24361. if (this.textures) {
  24362. for (var i = 0; i < this.textures.length; i++) {
  24363. var texture = this.textures[i];
  24364. if (texture && texture.renderList) {
  24365. texture.freeRenderingGroups();
  24366. }
  24367. }
  24368. }
  24369. };
  24370. Scene.prototype._isInIntermediateRendering = function () {
  24371. return this._intermediateRendering;
  24372. };
  24373. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  24374. this._activeMeshCandidateProvider = provider;
  24375. };
  24376. Scene.prototype.getActiveMeshCandidateProvider = function () {
  24377. return this._activeMeshCandidateProvider;
  24378. };
  24379. /**
  24380. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  24381. */
  24382. Scene.prototype.freezeActiveMeshes = function () {
  24383. if (!this.activeCamera) {
  24384. return this;
  24385. }
  24386. if (!this._frustumPlanes) {
  24387. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24388. }
  24389. this._evaluateActiveMeshes();
  24390. this._activeMeshesFrozen = true;
  24391. return this;
  24392. };
  24393. /**
  24394. * Use this function to restart evaluating active meshes on every frame
  24395. */
  24396. Scene.prototype.unfreezeActiveMeshes = function () {
  24397. this._activeMeshesFrozen = false;
  24398. return this;
  24399. };
  24400. Scene.prototype._evaluateActiveMeshes = function () {
  24401. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  24402. return;
  24403. }
  24404. if (!this.activeCamera) {
  24405. return;
  24406. }
  24407. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  24408. this.activeCamera._activeMeshes.reset();
  24409. this._activeMeshes.reset();
  24410. this._renderingManager.reset();
  24411. this._processedMaterials.reset();
  24412. this._activeParticleSystems.reset();
  24413. this._activeSkeletons.reset();
  24414. this._softwareSkinnedMeshes.reset();
  24415. if (this._boundingBoxRenderer) {
  24416. this._boundingBoxRenderer.reset();
  24417. }
  24418. // Meshes
  24419. var meshes;
  24420. var len;
  24421. var checkIsEnabled = true;
  24422. // Determine mesh candidates
  24423. if (this._activeMeshCandidateProvider !== undefined) {
  24424. // Use _activeMeshCandidateProvider
  24425. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  24426. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  24427. if (meshes !== undefined) {
  24428. len = meshes.length;
  24429. }
  24430. else {
  24431. len = 0;
  24432. }
  24433. }
  24434. else if (this._selectionOctree !== undefined) {
  24435. // Octree
  24436. var selection = this._selectionOctree.select(this._frustumPlanes);
  24437. meshes = selection.data;
  24438. len = selection.length;
  24439. }
  24440. else {
  24441. // Full scene traversal
  24442. len = this.meshes.length;
  24443. meshes = this.meshes;
  24444. }
  24445. // Check each mesh
  24446. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  24447. mesh = meshes[meshIndex];
  24448. if (mesh.isBlocked) {
  24449. continue;
  24450. }
  24451. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  24452. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  24453. continue;
  24454. }
  24455. mesh.computeWorldMatrix();
  24456. // Intersections
  24457. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  24458. this._meshesForIntersections.pushNoDuplicate(mesh);
  24459. }
  24460. // Switch to current LOD
  24461. meshLOD = mesh.getLOD(this.activeCamera);
  24462. if (meshLOD === undefined || meshLOD === null) {
  24463. continue;
  24464. }
  24465. mesh._preActivate();
  24466. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  24467. this._activeMeshes.push(mesh);
  24468. this.activeCamera._activeMeshes.push(mesh);
  24469. mesh._activate(this._renderId);
  24470. if (meshLOD !== mesh) {
  24471. meshLOD._activate(this._renderId);
  24472. }
  24473. this._activeMesh(mesh, meshLOD);
  24474. }
  24475. }
  24476. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  24477. // Particle systems
  24478. if (this.particlesEnabled) {
  24479. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  24480. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  24481. var particleSystem = this.particleSystems[particleIndex];
  24482. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  24483. continue;
  24484. }
  24485. var emitter = particleSystem.emitter;
  24486. if (!emitter.position || emitter.isEnabled()) {
  24487. this._activeParticleSystems.push(particleSystem);
  24488. particleSystem.animate();
  24489. this._renderingManager.dispatchParticles(particleSystem);
  24490. }
  24491. }
  24492. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  24493. }
  24494. };
  24495. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  24496. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  24497. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  24498. mesh.skeleton.prepare();
  24499. }
  24500. if (!mesh.computeBonesUsingShaders) {
  24501. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  24502. }
  24503. }
  24504. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  24505. var boundingInfo = sourceMesh.getBoundingInfo();
  24506. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  24507. }
  24508. if (mesh !== undefined && mesh !== null
  24509. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  24510. // Submeshes Octrees
  24511. var len;
  24512. var subMeshes;
  24513. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  24514. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  24515. len = intersections.length;
  24516. subMeshes = intersections.data;
  24517. }
  24518. else {
  24519. subMeshes = mesh.subMeshes;
  24520. len = subMeshes.length;
  24521. }
  24522. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  24523. subMesh = subMeshes[subIndex];
  24524. this._evaluateSubMesh(subMesh, mesh);
  24525. }
  24526. }
  24527. };
  24528. Scene.prototype.updateTransformMatrix = function (force) {
  24529. if (!this.activeCamera) {
  24530. return;
  24531. }
  24532. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  24533. };
  24534. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  24535. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  24536. };
  24537. Scene.prototype._renderForCamera = function (camera, rigParent) {
  24538. if (camera && camera._skipRendering) {
  24539. return;
  24540. }
  24541. var engine = this._engine;
  24542. this.activeCamera = camera;
  24543. if (!this.activeCamera)
  24544. throw new Error("Active camera not set");
  24545. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24546. // Viewport
  24547. engine.setViewport(this.activeCamera.viewport);
  24548. // Camera
  24549. this.resetCachedMaterial();
  24550. this._renderId++;
  24551. this.updateTransformMatrix();
  24552. if (camera._alternateCamera) {
  24553. this.updateAlternateTransformMatrix(camera._alternateCamera);
  24554. this._alternateRendering = true;
  24555. }
  24556. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  24557. // Meshes
  24558. this._evaluateActiveMeshes();
  24559. // Software skinning
  24560. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  24561. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  24562. mesh.applySkeleton(mesh.skeleton);
  24563. }
  24564. // Render targets
  24565. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24566. var needsRestoreFrameBuffer = false;
  24567. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  24568. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  24569. }
  24570. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  24571. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  24572. }
  24573. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  24574. this._intermediateRendering = true;
  24575. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24576. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  24577. var renderTarget = this._renderTargets.data[renderIndex];
  24578. if (renderTarget._shouldRender()) {
  24579. this._renderId++;
  24580. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  24581. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  24582. }
  24583. }
  24584. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  24585. this._intermediateRendering = false;
  24586. this._renderId++;
  24587. needsRestoreFrameBuffer = true; // Restore back buffer
  24588. }
  24589. // Render EffecttLayer Texture
  24590. var stencilState = this._engine.getStencilBuffer();
  24591. var renderEffects = false;
  24592. var needStencil = false;
  24593. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  24594. this._intermediateRendering = true;
  24595. for (var i = 0; i < this.effectLayers.length; i++) {
  24596. var effectLayer = this.effectLayers[i];
  24597. if (effectLayer.shouldRender() &&
  24598. (!effectLayer.camera ||
  24599. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  24600. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  24601. renderEffects = true;
  24602. needStencil = needStencil || effectLayer.needStencil();
  24603. var renderTarget = effectLayer._mainTexture;
  24604. if (renderTarget._shouldRender()) {
  24605. this._renderId++;
  24606. renderTarget.render(false, false);
  24607. needsRestoreFrameBuffer = true;
  24608. }
  24609. }
  24610. }
  24611. this._intermediateRendering = false;
  24612. this._renderId++;
  24613. }
  24614. if (needsRestoreFrameBuffer) {
  24615. engine.restoreDefaultFramebuffer(); // Restore back buffer
  24616. }
  24617. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24618. // Prepare Frame
  24619. this.postProcessManager._prepareFrame();
  24620. // Backgrounds
  24621. var layerIndex;
  24622. var layer;
  24623. if (this.layers.length) {
  24624. engine.setDepthBuffer(false);
  24625. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24626. layer = this.layers[layerIndex];
  24627. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24628. layer.render();
  24629. }
  24630. }
  24631. engine.setDepthBuffer(true);
  24632. }
  24633. // Activate effect Layer stencil
  24634. if (needStencil) {
  24635. this._engine.setStencilBuffer(true);
  24636. }
  24637. // Render
  24638. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  24639. this._renderingManager.render(null, null, true, true);
  24640. this.onAfterDrawPhaseObservable.notifyObservers(this);
  24641. // Restore effect Layer stencil
  24642. if (needStencil) {
  24643. this._engine.setStencilBuffer(stencilState);
  24644. }
  24645. // Bounding boxes
  24646. if (this._boundingBoxRenderer) {
  24647. this._boundingBoxRenderer.render();
  24648. }
  24649. // Lens flares
  24650. if (this.lensFlaresEnabled) {
  24651. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24652. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  24653. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  24654. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  24655. lensFlareSystem.render();
  24656. }
  24657. }
  24658. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  24659. }
  24660. // Foregrounds
  24661. if (this.layers.length) {
  24662. engine.setDepthBuffer(false);
  24663. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  24664. layer = this.layers[layerIndex];
  24665. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  24666. layer.render();
  24667. }
  24668. }
  24669. engine.setDepthBuffer(true);
  24670. }
  24671. // Effect Layer
  24672. if (renderEffects) {
  24673. engine.setDepthBuffer(false);
  24674. for (var i = 0; i < this.effectLayers.length; i++) {
  24675. if (this.effectLayers[i].shouldRender()) {
  24676. this.effectLayers[i].render();
  24677. }
  24678. }
  24679. engine.setDepthBuffer(true);
  24680. }
  24681. // Finalize frame
  24682. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  24683. // Reset some special arrays
  24684. this._renderTargets.reset();
  24685. this._alternateRendering = false;
  24686. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  24687. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  24688. };
  24689. Scene.prototype._processSubCameras = function (camera) {
  24690. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  24691. this._renderForCamera(camera);
  24692. return;
  24693. }
  24694. // rig cameras
  24695. for (var index = 0; index < camera._rigCameras.length; index++) {
  24696. this._renderForCamera(camera._rigCameras[index], camera);
  24697. }
  24698. this.activeCamera = camera;
  24699. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  24700. };
  24701. Scene.prototype._checkIntersections = function () {
  24702. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  24703. var sourceMesh = this._meshesForIntersections.data[index];
  24704. if (!sourceMesh.actionManager) {
  24705. continue;
  24706. }
  24707. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  24708. var action = sourceMesh.actionManager.actions[actionIndex];
  24709. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24710. var parameters = action.getTriggerParameter();
  24711. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  24712. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  24713. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  24714. if (areIntersecting && currentIntersectionInProgress === -1) {
  24715. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  24716. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24717. sourceMesh._intersectionsInProgress.push(otherMesh);
  24718. }
  24719. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24720. sourceMesh._intersectionsInProgress.push(otherMesh);
  24721. }
  24722. }
  24723. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  24724. //They intersected, and now they don't.
  24725. //is this trigger an exit trigger? execute an event.
  24726. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24727. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  24728. }
  24729. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  24730. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  24731. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  24732. }
  24733. }
  24734. }
  24735. }
  24736. }
  24737. };
  24738. Scene.prototype.render = function () {
  24739. if (this.isDisposed) {
  24740. return;
  24741. }
  24742. this._activeParticles.fetchNewFrame();
  24743. this._totalVertices.fetchNewFrame();
  24744. this._activeIndices.fetchNewFrame();
  24745. this._activeBones.fetchNewFrame();
  24746. this._meshesForIntersections.reset();
  24747. this.resetCachedMaterial();
  24748. this.onBeforeAnimationsObservable.notifyObservers(this);
  24749. // Actions
  24750. if (this.actionManager) {
  24751. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  24752. }
  24753. //Simplification Queue
  24754. if (this.simplificationQueue && !this.simplificationQueue.running) {
  24755. this.simplificationQueue.executeNext();
  24756. }
  24757. if (this._engine.isDeterministicLockStep()) {
  24758. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  24759. var defaultFPS = (60.0 / 1000.0);
  24760. var defaultFrameTime = 1000 / 60; // frame time in MS
  24761. if (this._physicsEngine) {
  24762. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  24763. }
  24764. var stepsTaken = 0;
  24765. var maxSubSteps = this._engine.getLockstepMaxSteps();
  24766. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  24767. internalSteps = Math.min(internalSteps, maxSubSteps);
  24768. do {
  24769. this.onBeforeStepObservable.notifyObservers(this);
  24770. // Animations
  24771. this._animationRatio = defaultFrameTime * defaultFPS;
  24772. this._animate();
  24773. this.onAfterAnimationsObservable.notifyObservers(this);
  24774. // Physics
  24775. if (this._physicsEngine) {
  24776. this.onBeforePhysicsObservable.notifyObservers(this);
  24777. this._physicsEngine._step(defaultFrameTime / 1000);
  24778. this.onAfterPhysicsObservable.notifyObservers(this);
  24779. }
  24780. this.onAfterStepObservable.notifyObservers(this);
  24781. this._currentStepId++;
  24782. stepsTaken++;
  24783. deltaTime -= defaultFrameTime;
  24784. } while (deltaTime > 0 && stepsTaken < internalSteps);
  24785. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  24786. }
  24787. else {
  24788. // Animations
  24789. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  24790. this._animationRatio = deltaTime * (60.0 / 1000.0);
  24791. this._animate();
  24792. this.onAfterAnimationsObservable.notifyObservers(this);
  24793. // Physics
  24794. if (this._physicsEngine) {
  24795. this.onBeforePhysicsObservable.notifyObservers(this);
  24796. this._physicsEngine._step(deltaTime / 1000.0);
  24797. this.onAfterPhysicsObservable.notifyObservers(this);
  24798. }
  24799. }
  24800. // update gamepad manager
  24801. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  24802. this._gamepadManager._checkGamepadsStatus();
  24803. }
  24804. // Update Cameras
  24805. if (this.activeCameras.length > 0) {
  24806. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24807. var camera = this.activeCameras[cameraIndex];
  24808. camera.update();
  24809. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24810. // rig cameras
  24811. for (var index = 0; index < camera._rigCameras.length; index++) {
  24812. camera._rigCameras[index].update();
  24813. }
  24814. }
  24815. }
  24816. }
  24817. else if (this.activeCamera) {
  24818. this.activeCamera.update();
  24819. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  24820. // rig cameras
  24821. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  24822. this.activeCamera._rigCameras[index].update();
  24823. }
  24824. }
  24825. }
  24826. // Before render
  24827. this.onBeforeRenderObservable.notifyObservers(this);
  24828. // Customs render targets
  24829. this.OnBeforeRenderTargetsRenderObservable.notifyObservers(this);
  24830. var engine = this.getEngine();
  24831. var currentActiveCamera = this.activeCamera;
  24832. if (this.renderTargetsEnabled) {
  24833. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24834. this._intermediateRendering = true;
  24835. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  24836. var renderTarget = this.customRenderTargets[customIndex];
  24837. if (renderTarget._shouldRender()) {
  24838. this._renderId++;
  24839. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  24840. if (!this.activeCamera)
  24841. throw new Error("Active camera not set");
  24842. // Viewport
  24843. engine.setViewport(this.activeCamera.viewport);
  24844. // Camera
  24845. this.updateTransformMatrix();
  24846. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  24847. }
  24848. }
  24849. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  24850. this._intermediateRendering = false;
  24851. this._renderId++;
  24852. }
  24853. // Restore back buffer
  24854. if (this.customRenderTargets.length > 0) {
  24855. engine.restoreDefaultFramebuffer();
  24856. }
  24857. this.OnAfterRenderTargetsRenderObservable.notifyObservers(this);
  24858. this.activeCamera = currentActiveCamera;
  24859. // Procedural textures
  24860. if (this.proceduralTexturesEnabled) {
  24861. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24862. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  24863. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  24864. if (proceduralTexture._shouldRender()) {
  24865. proceduralTexture.render();
  24866. }
  24867. }
  24868. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  24869. }
  24870. // Clear
  24871. if (this.autoClearDepthAndStencil || this.autoClear) {
  24872. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  24873. }
  24874. // Shadows
  24875. if (this.shadowsEnabled) {
  24876. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  24877. var light = this.lights[lightIndex];
  24878. var shadowGenerator = light.getShadowGenerator();
  24879. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  24880. var shadowMap = (shadowGenerator.getShadowMap());
  24881. if (this.textures.indexOf(shadowMap) !== -1) {
  24882. this._renderTargets.push(shadowMap);
  24883. }
  24884. }
  24885. }
  24886. }
  24887. // Depth renderer
  24888. for (var key in this._depthRenderer) {
  24889. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  24890. }
  24891. // Geometry renderer
  24892. if (this._geometryBufferRenderer) {
  24893. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  24894. }
  24895. // RenderPipeline
  24896. if (this._postProcessRenderPipelineManager) {
  24897. this._postProcessRenderPipelineManager.update();
  24898. }
  24899. // Multi-cameras?
  24900. if (this.activeCameras.length > 0) {
  24901. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  24902. if (cameraIndex > 0) {
  24903. this._engine.clear(null, false, true, true);
  24904. }
  24905. this._processSubCameras(this.activeCameras[cameraIndex]);
  24906. }
  24907. }
  24908. else {
  24909. if (!this.activeCamera) {
  24910. throw new Error("No camera defined");
  24911. }
  24912. this._processSubCameras(this.activeCamera);
  24913. }
  24914. // Intersection checks
  24915. this._checkIntersections();
  24916. // Update the audio listener attached to the camera
  24917. if (BABYLON.AudioEngine) {
  24918. this._updateAudioParameters();
  24919. }
  24920. // After render
  24921. if (this.afterRender) {
  24922. this.afterRender();
  24923. }
  24924. this.onAfterRenderObservable.notifyObservers(this);
  24925. // Cleaning
  24926. for (var index = 0; index < this._toBeDisposed.length; index++) {
  24927. var data = this._toBeDisposed.data[index];
  24928. if (data) {
  24929. data.dispose();
  24930. }
  24931. this._toBeDisposed[index] = null;
  24932. }
  24933. this._toBeDisposed.reset();
  24934. if (this.dumpNextRenderTargets) {
  24935. this.dumpNextRenderTargets = false;
  24936. }
  24937. this._activeBones.addCount(0, true);
  24938. this._activeIndices.addCount(0, true);
  24939. this._activeParticles.addCount(0, true);
  24940. };
  24941. Scene.prototype._updateAudioParameters = function () {
  24942. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  24943. return;
  24944. }
  24945. var listeningCamera;
  24946. var audioEngine = BABYLON.Engine.audioEngine;
  24947. if (this.activeCameras.length > 0) {
  24948. listeningCamera = this.activeCameras[0];
  24949. }
  24950. else {
  24951. listeningCamera = this.activeCamera;
  24952. }
  24953. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  24954. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  24955. // for VR cameras
  24956. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  24957. listeningCamera = listeningCamera.rigCameras[0];
  24958. }
  24959. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  24960. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  24961. cameraDirection.normalize();
  24962. // To avoid some errors on GearVR
  24963. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  24964. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  24965. }
  24966. var i;
  24967. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  24968. var sound = this.mainSoundTrack.soundCollection[i];
  24969. if (sound.useCustomAttenuation) {
  24970. sound.updateDistanceFromListener();
  24971. }
  24972. }
  24973. for (i = 0; i < this.soundTracks.length; i++) {
  24974. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  24975. sound = this.soundTracks[i].soundCollection[j];
  24976. if (sound.useCustomAttenuation) {
  24977. sound.updateDistanceFromListener();
  24978. }
  24979. }
  24980. }
  24981. }
  24982. };
  24983. Object.defineProperty(Scene.prototype, "audioEnabled", {
  24984. // Audio
  24985. get: function () {
  24986. return this._audioEnabled;
  24987. },
  24988. set: function (value) {
  24989. this._audioEnabled = value;
  24990. if (BABYLON.AudioEngine) {
  24991. if (this._audioEnabled) {
  24992. this._enableAudio();
  24993. }
  24994. else {
  24995. this._disableAudio();
  24996. }
  24997. }
  24998. },
  24999. enumerable: true,
  25000. configurable: true
  25001. });
  25002. Scene.prototype._disableAudio = function () {
  25003. var i;
  25004. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  25005. this.mainSoundTrack.soundCollection[i].pause();
  25006. }
  25007. for (i = 0; i < this.soundTracks.length; i++) {
  25008. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  25009. this.soundTracks[i].soundCollection[j].pause();
  25010. }
  25011. }
  25012. };
  25013. Scene.prototype._enableAudio = function () {
  25014. var i;
  25015. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  25016. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  25017. this.mainSoundTrack.soundCollection[i].play();
  25018. }
  25019. }
  25020. for (i = 0; i < this.soundTracks.length; i++) {
  25021. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  25022. if (this.soundTracks[i].soundCollection[j].isPaused) {
  25023. this.soundTracks[i].soundCollection[j].play();
  25024. }
  25025. }
  25026. }
  25027. };
  25028. Object.defineProperty(Scene.prototype, "headphone", {
  25029. get: function () {
  25030. return this._headphone;
  25031. },
  25032. set: function (value) {
  25033. this._headphone = value;
  25034. if (BABYLON.AudioEngine) {
  25035. if (this._headphone) {
  25036. this._switchAudioModeForHeadphones();
  25037. }
  25038. else {
  25039. this._switchAudioModeForNormalSpeakers();
  25040. }
  25041. }
  25042. },
  25043. enumerable: true,
  25044. configurable: true
  25045. });
  25046. Scene.prototype._switchAudioModeForHeadphones = function () {
  25047. this.mainSoundTrack.switchPanningModelToHRTF();
  25048. for (var i = 0; i < this.soundTracks.length; i++) {
  25049. this.soundTracks[i].switchPanningModelToHRTF();
  25050. }
  25051. };
  25052. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  25053. this.mainSoundTrack.switchPanningModelToEqualPower();
  25054. for (var i = 0; i < this.soundTracks.length; i++) {
  25055. this.soundTracks[i].switchPanningModelToEqualPower();
  25056. }
  25057. };
  25058. /**
  25059. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  25060. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  25061. * @returns the created depth renderer
  25062. */
  25063. Scene.prototype.enableDepthRenderer = function (camera) {
  25064. camera = camera || this.activeCamera;
  25065. if (!camera) {
  25066. throw "No camera available to enable depth renderer";
  25067. }
  25068. if (!this._depthRenderer[camera.id]) {
  25069. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, BABYLON.Engine.TEXTURETYPE_FLOAT, camera);
  25070. }
  25071. return this._depthRenderer[camera.id];
  25072. };
  25073. /**
  25074. * Disables a depth renderer for a given camera
  25075. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  25076. */
  25077. Scene.prototype.disableDepthRenderer = function (camera) {
  25078. camera = camera || this.activeCamera;
  25079. if (!camera || !this._depthRenderer[camera.id]) {
  25080. return;
  25081. }
  25082. this._depthRenderer[camera.id].dispose();
  25083. delete this._depthRenderer[camera.id];
  25084. };
  25085. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  25086. if (ratio === void 0) { ratio = 1; }
  25087. if (this._geometryBufferRenderer) {
  25088. return this._geometryBufferRenderer;
  25089. }
  25090. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  25091. if (!this._geometryBufferRenderer.isSupported) {
  25092. this._geometryBufferRenderer = null;
  25093. }
  25094. return this._geometryBufferRenderer;
  25095. };
  25096. Scene.prototype.disableGeometryBufferRenderer = function () {
  25097. if (!this._geometryBufferRenderer) {
  25098. return;
  25099. }
  25100. this._geometryBufferRenderer.dispose();
  25101. this._geometryBufferRenderer = null;
  25102. };
  25103. Scene.prototype.freezeMaterials = function () {
  25104. for (var i = 0; i < this.materials.length; i++) {
  25105. this.materials[i].freeze();
  25106. }
  25107. };
  25108. Scene.prototype.unfreezeMaterials = function () {
  25109. for (var i = 0; i < this.materials.length; i++) {
  25110. this.materials[i].unfreeze();
  25111. }
  25112. };
  25113. Scene.prototype.dispose = function () {
  25114. this.beforeRender = null;
  25115. this.afterRender = null;
  25116. this.skeletons = [];
  25117. this.morphTargetManagers = [];
  25118. this.importedMeshesFiles = new Array();
  25119. this.stopAllAnimations();
  25120. this.resetCachedMaterial();
  25121. for (var key in this._depthRenderer) {
  25122. this._depthRenderer[key].dispose();
  25123. }
  25124. if (this._gamepadManager) {
  25125. this._gamepadManager.dispose();
  25126. this._gamepadManager = null;
  25127. }
  25128. // Smart arrays
  25129. if (this.activeCamera) {
  25130. this.activeCamera._activeMeshes.dispose();
  25131. this.activeCamera = null;
  25132. }
  25133. this._activeMeshes.dispose();
  25134. this._renderingManager.dispose();
  25135. this._processedMaterials.dispose();
  25136. this._activeParticleSystems.dispose();
  25137. this._activeSkeletons.dispose();
  25138. this._softwareSkinnedMeshes.dispose();
  25139. this._renderTargets.dispose();
  25140. this._registeredForLateAnimationBindings.dispose();
  25141. if (this._boundingBoxRenderer) {
  25142. this._boundingBoxRenderer.dispose();
  25143. }
  25144. this._meshesForIntersections.dispose();
  25145. this._toBeDisposed.dispose();
  25146. // Abort active requests
  25147. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  25148. var request = _a[_i];
  25149. request.abort();
  25150. }
  25151. // Debug layer
  25152. if (this._debugLayer) {
  25153. this._debugLayer.hide();
  25154. }
  25155. // Events
  25156. this.onDisposeObservable.notifyObservers(this);
  25157. this.onDisposeObservable.clear();
  25158. this.onBeforeRenderObservable.clear();
  25159. this.onAfterRenderObservable.clear();
  25160. this.OnBeforeRenderTargetsRenderObservable.clear();
  25161. this.OnAfterRenderTargetsRenderObservable.clear();
  25162. this.onAfterStepObservable.clear();
  25163. this.onBeforeStepObservable.clear();
  25164. this.onBeforeActiveMeshesEvaluationObservable.clear();
  25165. this.onAfterActiveMeshesEvaluationObservable.clear();
  25166. this.onBeforeParticlesRenderingObservable.clear();
  25167. this.onAfterParticlesRenderingObservable.clear();
  25168. this.onBeforeSpritesRenderingObservable.clear();
  25169. this.onAfterSpritesRenderingObservable.clear();
  25170. this.onBeforeDrawPhaseObservable.clear();
  25171. this.onAfterDrawPhaseObservable.clear();
  25172. this.onBeforePhysicsObservable.clear();
  25173. this.onAfterPhysicsObservable.clear();
  25174. this.onBeforeAnimationsObservable.clear();
  25175. this.onAfterAnimationsObservable.clear();
  25176. this.onDataLoadedObservable.clear();
  25177. this.detachControl();
  25178. // Release sounds & sounds tracks
  25179. if (BABYLON.AudioEngine) {
  25180. this.disposeSounds();
  25181. }
  25182. // VR Helper
  25183. if (this.VRHelper) {
  25184. this.VRHelper.dispose();
  25185. }
  25186. // Detach cameras
  25187. var canvas = this._engine.getRenderingCanvas();
  25188. if (canvas) {
  25189. var index;
  25190. for (index = 0; index < this.cameras.length; index++) {
  25191. this.cameras[index].detachControl(canvas);
  25192. }
  25193. }
  25194. // Release animation groups
  25195. while (this.animationGroups.length) {
  25196. this.animationGroups[0].dispose();
  25197. }
  25198. // Release lights
  25199. while (this.lights.length) {
  25200. this.lights[0].dispose();
  25201. }
  25202. // Release meshes
  25203. while (this.meshes.length) {
  25204. this.meshes[0].dispose(true);
  25205. }
  25206. while (this.transformNodes.length) {
  25207. this.removeTransformNode(this.transformNodes[0]);
  25208. }
  25209. // Release cameras
  25210. while (this.cameras.length) {
  25211. this.cameras[0].dispose();
  25212. }
  25213. // Release materials
  25214. if (this.defaultMaterial) {
  25215. this.defaultMaterial.dispose();
  25216. }
  25217. while (this.multiMaterials.length) {
  25218. this.multiMaterials[0].dispose();
  25219. }
  25220. while (this.materials.length) {
  25221. this.materials[0].dispose();
  25222. }
  25223. // Release particles
  25224. while (this.particleSystems.length) {
  25225. this.particleSystems[0].dispose();
  25226. }
  25227. // Release sprites
  25228. while (this.spriteManagers.length) {
  25229. this.spriteManagers[0].dispose();
  25230. }
  25231. // Release postProcesses
  25232. while (this.postProcesses.length) {
  25233. this.postProcesses[0].dispose();
  25234. }
  25235. // Release layers
  25236. while (this.layers.length) {
  25237. this.layers[0].dispose();
  25238. }
  25239. while (this.effectLayers.length) {
  25240. this.effectLayers[0].dispose();
  25241. }
  25242. // Release textures
  25243. while (this.textures.length) {
  25244. this.textures[0].dispose();
  25245. }
  25246. // Release UBO
  25247. this._sceneUbo.dispose();
  25248. if (this._alternateSceneUbo) {
  25249. this._alternateSceneUbo.dispose();
  25250. }
  25251. // Post-processes
  25252. this.postProcessManager.dispose();
  25253. if (this._postProcessRenderPipelineManager) {
  25254. this._postProcessRenderPipelineManager.dispose();
  25255. }
  25256. // Physics
  25257. if (this._physicsEngine) {
  25258. this.disablePhysicsEngine();
  25259. }
  25260. // Remove from engine
  25261. index = this._engine.scenes.indexOf(this);
  25262. if (index > -1) {
  25263. this._engine.scenes.splice(index, 1);
  25264. }
  25265. this._engine.wipeCaches(true);
  25266. this._isDisposed = true;
  25267. };
  25268. Object.defineProperty(Scene.prototype, "isDisposed", {
  25269. get: function () {
  25270. return this._isDisposed;
  25271. },
  25272. enumerable: true,
  25273. configurable: true
  25274. });
  25275. // Release sounds & sounds tracks
  25276. Scene.prototype.disposeSounds = function () {
  25277. if (!this._mainSoundTrack) {
  25278. return;
  25279. }
  25280. this.mainSoundTrack.dispose();
  25281. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  25282. this.soundTracks[scIndex].dispose();
  25283. }
  25284. };
  25285. // Octrees
  25286. /**
  25287. * Get the world extend vectors with an optional filter
  25288. *
  25289. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  25290. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  25291. */
  25292. Scene.prototype.getWorldExtends = function (filterPredicate) {
  25293. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  25294. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  25295. filterPredicate = filterPredicate || (function () { return true; });
  25296. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  25297. mesh.computeWorldMatrix(true);
  25298. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  25299. return;
  25300. }
  25301. var boundingInfo = mesh.getBoundingInfo();
  25302. var minBox = boundingInfo.boundingBox.minimumWorld;
  25303. var maxBox = boundingInfo.boundingBox.maximumWorld;
  25304. BABYLON.Tools.CheckExtends(minBox, min, max);
  25305. BABYLON.Tools.CheckExtends(maxBox, min, max);
  25306. });
  25307. return {
  25308. min: min,
  25309. max: max
  25310. };
  25311. };
  25312. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  25313. if (maxCapacity === void 0) { maxCapacity = 64; }
  25314. if (maxDepth === void 0) { maxDepth = 2; }
  25315. if (!this._selectionOctree) {
  25316. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  25317. }
  25318. var worldExtends = this.getWorldExtends();
  25319. // Update octree
  25320. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  25321. return this._selectionOctree;
  25322. };
  25323. // Picking
  25324. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  25325. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  25326. var result = BABYLON.Ray.Zero();
  25327. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  25328. return result;
  25329. };
  25330. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  25331. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  25332. var engine = this._engine;
  25333. if (!camera) {
  25334. if (!this.activeCamera)
  25335. throw new Error("Active camera not set");
  25336. camera = this.activeCamera;
  25337. }
  25338. var cameraViewport = camera.viewport;
  25339. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  25340. // Moving coordinates to local viewport world
  25341. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  25342. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  25343. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  25344. return this;
  25345. };
  25346. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  25347. var result = BABYLON.Ray.Zero();
  25348. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  25349. return result;
  25350. };
  25351. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  25352. if (!BABYLON.PickingInfo) {
  25353. return this;
  25354. }
  25355. var engine = this._engine;
  25356. if (!camera) {
  25357. if (!this.activeCamera)
  25358. throw new Error("Active camera not set");
  25359. camera = this.activeCamera;
  25360. }
  25361. var cameraViewport = camera.viewport;
  25362. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  25363. var identity = BABYLON.Matrix.Identity();
  25364. // Moving coordinates to local viewport world
  25365. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  25366. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  25367. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  25368. return this;
  25369. };
  25370. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  25371. if (!BABYLON.PickingInfo) {
  25372. return null;
  25373. }
  25374. var pickingInfo = null;
  25375. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  25376. var mesh = this.meshes[meshIndex];
  25377. if (predicate) {
  25378. if (!predicate(mesh)) {
  25379. continue;
  25380. }
  25381. }
  25382. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  25383. continue;
  25384. }
  25385. var world = mesh.getWorldMatrix();
  25386. var ray = rayFunction(world);
  25387. var result = mesh.intersects(ray, fastCheck);
  25388. if (!result || !result.hit)
  25389. continue;
  25390. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  25391. continue;
  25392. pickingInfo = result;
  25393. if (fastCheck) {
  25394. break;
  25395. }
  25396. }
  25397. return pickingInfo || new BABYLON.PickingInfo();
  25398. };
  25399. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  25400. if (!BABYLON.PickingInfo) {
  25401. return null;
  25402. }
  25403. var pickingInfos = new Array();
  25404. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  25405. var mesh = this.meshes[meshIndex];
  25406. if (predicate) {
  25407. if (!predicate(mesh)) {
  25408. continue;
  25409. }
  25410. }
  25411. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  25412. continue;
  25413. }
  25414. var world = mesh.getWorldMatrix();
  25415. var ray = rayFunction(world);
  25416. var result = mesh.intersects(ray, false);
  25417. if (!result || !result.hit)
  25418. continue;
  25419. pickingInfos.push(result);
  25420. }
  25421. return pickingInfos;
  25422. };
  25423. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  25424. if (!BABYLON.PickingInfo) {
  25425. return null;
  25426. }
  25427. var pickingInfo = null;
  25428. if (!camera) {
  25429. if (!this.activeCamera) {
  25430. return null;
  25431. }
  25432. camera = this.activeCamera;
  25433. }
  25434. if (this.spriteManagers.length > 0) {
  25435. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  25436. var spriteManager = this.spriteManagers[spriteIndex];
  25437. if (!spriteManager.isPickable) {
  25438. continue;
  25439. }
  25440. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  25441. if (!result || !result.hit)
  25442. continue;
  25443. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  25444. continue;
  25445. pickingInfo = result;
  25446. if (fastCheck) {
  25447. break;
  25448. }
  25449. }
  25450. }
  25451. return pickingInfo || new BABYLON.PickingInfo();
  25452. };
  25453. /** Launch a ray to try to pick a mesh in the scene
  25454. * @param x position on screen
  25455. * @param y position on screen
  25456. * @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
  25457. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25458. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25459. */
  25460. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  25461. var _this = this;
  25462. if (!BABYLON.PickingInfo) {
  25463. return null;
  25464. }
  25465. return this._internalPick(function (world) {
  25466. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  25467. return _this._tempPickingRay;
  25468. }, predicate, fastCheck);
  25469. };
  25470. /** Launch a ray to try to pick a sprite in the scene
  25471. * @param x position on screen
  25472. * @param y position on screen
  25473. * @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
  25474. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25475. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25476. */
  25477. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  25478. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  25479. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  25480. };
  25481. /** Use the given ray to pick a mesh in the scene
  25482. * @param ray The ray to use to pick meshes
  25483. * @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
  25484. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  25485. */
  25486. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  25487. var _this = this;
  25488. return this._internalPick(function (world) {
  25489. if (!_this._pickWithRayInverseMatrix) {
  25490. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25491. }
  25492. world.invertToRef(_this._pickWithRayInverseMatrix);
  25493. if (!_this._cachedRayForTransform) {
  25494. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25495. }
  25496. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25497. return _this._cachedRayForTransform;
  25498. }, predicate, fastCheck);
  25499. };
  25500. /**
  25501. * Launch a ray to try to pick a mesh in the scene
  25502. * @param x X position on screen
  25503. * @param y Y position on screen
  25504. * @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
  25505. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  25506. */
  25507. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  25508. var _this = this;
  25509. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  25510. };
  25511. /**
  25512. * Launch a ray to try to pick a mesh in the scene
  25513. * @param ray Ray to use
  25514. * @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
  25515. */
  25516. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  25517. var _this = this;
  25518. return this._internalMultiPick(function (world) {
  25519. if (!_this._pickWithRayInverseMatrix) {
  25520. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  25521. }
  25522. world.invertToRef(_this._pickWithRayInverseMatrix);
  25523. if (!_this._cachedRayForTransform) {
  25524. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  25525. }
  25526. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  25527. return _this._cachedRayForTransform;
  25528. }, predicate);
  25529. };
  25530. Scene.prototype.setPointerOverMesh = function (mesh) {
  25531. if (this._pointerOverMesh === mesh) {
  25532. return;
  25533. }
  25534. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25535. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25536. }
  25537. this._pointerOverMesh = mesh;
  25538. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  25539. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  25540. }
  25541. };
  25542. Scene.prototype.getPointerOverMesh = function () {
  25543. return this._pointerOverMesh;
  25544. };
  25545. Scene.prototype.setPointerOverSprite = function (sprite) {
  25546. if (this._pointerOverSprite === sprite) {
  25547. return;
  25548. }
  25549. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25550. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25551. }
  25552. this._pointerOverSprite = sprite;
  25553. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  25554. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  25555. }
  25556. };
  25557. Scene.prototype.getPointerOverSprite = function () {
  25558. return this._pointerOverSprite;
  25559. };
  25560. // Physics
  25561. Scene.prototype.getPhysicsEngine = function () {
  25562. return this._physicsEngine;
  25563. };
  25564. /**
  25565. * Enables physics to the current scene
  25566. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  25567. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  25568. * @return {boolean} was the physics engine initialized
  25569. */
  25570. Scene.prototype.enablePhysics = function (gravity, plugin) {
  25571. if (gravity === void 0) { gravity = null; }
  25572. if (this._physicsEngine) {
  25573. return true;
  25574. }
  25575. try {
  25576. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  25577. return true;
  25578. }
  25579. catch (e) {
  25580. BABYLON.Tools.Error(e.message);
  25581. return false;
  25582. }
  25583. };
  25584. Scene.prototype.disablePhysicsEngine = function () {
  25585. if (!this._physicsEngine) {
  25586. return;
  25587. }
  25588. this._physicsEngine.dispose();
  25589. this._physicsEngine = null;
  25590. };
  25591. Scene.prototype.isPhysicsEnabled = function () {
  25592. return this._physicsEngine !== undefined;
  25593. };
  25594. Scene.prototype.deleteCompoundImpostor = function (compound) {
  25595. var mesh = compound.parts[0].mesh;
  25596. if (mesh.physicsImpostor) {
  25597. mesh.physicsImpostor.dispose();
  25598. mesh.physicsImpostor = null;
  25599. }
  25600. };
  25601. // Misc.
  25602. Scene.prototype._rebuildGeometries = function () {
  25603. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  25604. var geometry = _a[_i];
  25605. geometry._rebuild();
  25606. }
  25607. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  25608. var mesh = _c[_b];
  25609. mesh._rebuild();
  25610. }
  25611. if (this.postProcessManager) {
  25612. this.postProcessManager._rebuild();
  25613. }
  25614. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  25615. var layer = _e[_d];
  25616. layer._rebuild();
  25617. }
  25618. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  25619. var effectLayer = _g[_f];
  25620. effectLayer._rebuild();
  25621. }
  25622. if (this._boundingBoxRenderer) {
  25623. this._boundingBoxRenderer._rebuild();
  25624. }
  25625. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  25626. var system = _j[_h];
  25627. system.rebuild();
  25628. }
  25629. if (this._postProcessRenderPipelineManager) {
  25630. this._postProcessRenderPipelineManager._rebuild();
  25631. }
  25632. };
  25633. Scene.prototype._rebuildTextures = function () {
  25634. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  25635. var texture = _a[_i];
  25636. texture._rebuild();
  25637. }
  25638. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25639. };
  25640. /**
  25641. * Creates a default light for the scene.
  25642. * @param replace Whether to replace the existing lights in the scene.
  25643. */
  25644. Scene.prototype.createDefaultLight = function (replace) {
  25645. if (replace === void 0) { replace = false; }
  25646. // Dispose existing light in replace mode.
  25647. if (replace) {
  25648. if (this.lights) {
  25649. for (var i = 0; i < this.lights.length; i++) {
  25650. this.lights[i].dispose();
  25651. }
  25652. }
  25653. }
  25654. // Light
  25655. if (this.lights.length === 0) {
  25656. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  25657. }
  25658. };
  25659. /**
  25660. * Creates a default camera for the scene.
  25661. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  25662. * @param replace Whether to replace the existing active camera in the scene.
  25663. * @param attachCameraControls Whether to attach camera controls to the canvas.
  25664. */
  25665. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  25666. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25667. if (replace === void 0) { replace = false; }
  25668. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25669. // Dispose existing camera in replace mode.
  25670. if (replace) {
  25671. if (this.activeCamera) {
  25672. this.activeCamera.dispose();
  25673. this.activeCamera = null;
  25674. }
  25675. }
  25676. // Camera
  25677. if (!this.activeCamera) {
  25678. var worldExtends = this.getWorldExtends();
  25679. var worldSize = worldExtends.max.subtract(worldExtends.min);
  25680. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  25681. var camera;
  25682. var radius = worldSize.length() * 1.5;
  25683. // empty scene scenario!
  25684. if (!isFinite(radius)) {
  25685. radius = 1;
  25686. worldCenter.copyFromFloats(0, 0, 0);
  25687. }
  25688. if (createArcRotateCamera) {
  25689. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  25690. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  25691. arcRotateCamera.wheelPrecision = 100 / radius;
  25692. camera = arcRotateCamera;
  25693. }
  25694. else {
  25695. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  25696. freeCamera.setTarget(worldCenter);
  25697. camera = freeCamera;
  25698. }
  25699. camera.minZ = radius * 0.01;
  25700. camera.maxZ = radius * 1000;
  25701. camera.speed = radius * 0.2;
  25702. this.activeCamera = camera;
  25703. var canvas = this.getEngine().getRenderingCanvas();
  25704. if (attachCameraControls && canvas) {
  25705. camera.attachControl(canvas);
  25706. }
  25707. }
  25708. };
  25709. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  25710. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  25711. if (replace === void 0) { replace = false; }
  25712. if (attachCameraControls === void 0) { attachCameraControls = false; }
  25713. this.createDefaultLight(replace);
  25714. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  25715. };
  25716. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  25717. if (pbr === void 0) { pbr = false; }
  25718. if (scale === void 0) { scale = 1000; }
  25719. if (blur === void 0) { blur = 0; }
  25720. if (environmentTexture) {
  25721. this.environmentTexture = environmentTexture;
  25722. }
  25723. if (!this.environmentTexture) {
  25724. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  25725. return null;
  25726. }
  25727. // Skybox
  25728. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  25729. if (pbr) {
  25730. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  25731. hdrSkyboxMaterial.backFaceCulling = false;
  25732. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25733. if (hdrSkyboxMaterial.reflectionTexture) {
  25734. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25735. }
  25736. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  25737. hdrSkyboxMaterial.disableLighting = true;
  25738. hdrSkyboxMaterial.twoSidedLighting = true;
  25739. hdrSkybox.infiniteDistance = true;
  25740. hdrSkybox.material = hdrSkyboxMaterial;
  25741. }
  25742. else {
  25743. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  25744. skyboxMaterial.backFaceCulling = false;
  25745. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  25746. if (skyboxMaterial.reflectionTexture) {
  25747. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  25748. }
  25749. skyboxMaterial.disableLighting = true;
  25750. hdrSkybox.infiniteDistance = true;
  25751. hdrSkybox.material = skyboxMaterial;
  25752. }
  25753. return hdrSkybox;
  25754. };
  25755. Scene.prototype.createDefaultEnvironment = function (options) {
  25756. if (BABYLON.EnvironmentHelper) {
  25757. return new BABYLON.EnvironmentHelper(options, this);
  25758. }
  25759. return null;
  25760. };
  25761. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  25762. if (webVROptions === void 0) { webVROptions = {}; }
  25763. return new BABYLON.VRExperienceHelper(this, webVROptions);
  25764. };
  25765. // Tags
  25766. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  25767. if (tagsQuery === undefined) {
  25768. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  25769. return list;
  25770. }
  25771. var listByTags = [];
  25772. forEach = forEach || (function (item) { return; });
  25773. for (var i in list) {
  25774. var item = list[i];
  25775. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  25776. listByTags.push(item);
  25777. forEach(item);
  25778. }
  25779. }
  25780. return listByTags;
  25781. };
  25782. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  25783. return this._getByTags(this.meshes, tagsQuery, forEach);
  25784. };
  25785. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  25786. return this._getByTags(this.cameras, tagsQuery, forEach);
  25787. };
  25788. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  25789. return this._getByTags(this.lights, tagsQuery, forEach);
  25790. };
  25791. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  25792. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  25793. };
  25794. /**
  25795. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  25796. * This allowed control for front to back rendering or reversly depending of the special needs.
  25797. *
  25798. * @param renderingGroupId The rendering group id corresponding to its index
  25799. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  25800. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  25801. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  25802. */
  25803. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  25804. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  25805. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  25806. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  25807. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  25808. };
  25809. /**
  25810. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  25811. *
  25812. * @param renderingGroupId The rendering group id corresponding to its index
  25813. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  25814. * @param depth Automatically clears depth between groups if true and autoClear is true.
  25815. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  25816. */
  25817. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  25818. if (depth === void 0) { depth = true; }
  25819. if (stencil === void 0) { stencil = true; }
  25820. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  25821. };
  25822. /**
  25823. * Will flag all materials as dirty to trigger new shader compilation
  25824. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  25825. */
  25826. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  25827. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  25828. var material = _a[_i];
  25829. if (predicate && !predicate(material)) {
  25830. continue;
  25831. }
  25832. material.markAsDirty(flag);
  25833. }
  25834. };
  25835. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  25836. var _this = this;
  25837. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  25838. this._activeRequests.push(request);
  25839. request.onCompleteObservable.add(function (request) {
  25840. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  25841. });
  25842. return request;
  25843. };
  25844. /** @ignore */
  25845. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  25846. var _this = this;
  25847. return new Promise(function (resolve, reject) {
  25848. _this._loadFile(url, function (data) {
  25849. resolve(data);
  25850. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  25851. reject(exception);
  25852. });
  25853. });
  25854. };
  25855. // Statics
  25856. Scene._FOGMODE_NONE = 0;
  25857. Scene._FOGMODE_EXP = 1;
  25858. Scene._FOGMODE_EXP2 = 2;
  25859. Scene._FOGMODE_LINEAR = 3;
  25860. Scene._uniqueIdCounter = 0;
  25861. Scene.MinDeltaTime = 1.0;
  25862. Scene.MaxDeltaTime = 1000.0;
  25863. /** The distance in pixel that you have to move to prevent some events */
  25864. Scene.DragMovementThreshold = 10; // in pixels
  25865. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  25866. Scene.LongPressDelay = 500; // in milliseconds
  25867. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  25868. Scene.DoubleClickDelay = 300; // in milliseconds
  25869. /** If you need to check double click without raising a single click at first click, enable this flag */
  25870. Scene.ExclusiveDoubleClickMode = false;
  25871. return Scene;
  25872. }());
  25873. BABYLON.Scene = Scene;
  25874. })(BABYLON || (BABYLON = {}));
  25875. //# sourceMappingURL=babylon.scene.js.map
  25876. "use strict";
  25877. var BABYLON;
  25878. (function (BABYLON) {
  25879. /**
  25880. * Set of assets to keep when moving a scene into an asset container.
  25881. */
  25882. var KeepAssets = /** @class */ (function () {
  25883. function KeepAssets() {
  25884. /**
  25885. * Cameras to keep.
  25886. */
  25887. this.cameras = new Array();
  25888. /**
  25889. * Lights to keep.
  25890. */
  25891. this.lights = new Array();
  25892. /**
  25893. * Meshes to keep.
  25894. */
  25895. this.meshes = new Array();
  25896. /**
  25897. * Skeletons to keep.
  25898. */
  25899. this.skeletons = new Array();
  25900. /**
  25901. * ParticleSystems to keep.
  25902. */
  25903. this.particleSystems = new Array();
  25904. /**
  25905. * Animations to keep.
  25906. */
  25907. this.animations = new Array();
  25908. /**
  25909. * MultiMaterials to keep.
  25910. */
  25911. this.multiMaterials = new Array();
  25912. /**
  25913. * Materials to keep.
  25914. */
  25915. this.materials = new Array();
  25916. /**
  25917. * MorphTargetManagers to keep.
  25918. */
  25919. this.morphTargetManagers = new Array();
  25920. /**
  25921. * Geometries to keep.
  25922. */
  25923. this.geometries = new Array();
  25924. /**
  25925. * TransformNodes to keep.
  25926. */
  25927. this.transformNodes = new Array();
  25928. /**
  25929. * LensFlareSystems to keep.
  25930. */
  25931. this.lensFlareSystems = new Array();
  25932. /**
  25933. * ShadowGenerators to keep.
  25934. */
  25935. this.shadowGenerators = new Array();
  25936. /**
  25937. * ActionManagers to keep.
  25938. */
  25939. this.actionManagers = new Array();
  25940. /**
  25941. * Sounds to keep.
  25942. */
  25943. this.sounds = new Array();
  25944. }
  25945. return KeepAssets;
  25946. }());
  25947. BABYLON.KeepAssets = KeepAssets;
  25948. /**
  25949. * Container with a set of assets that can be added or removed from a scene.
  25950. */
  25951. var AssetContainer = /** @class */ (function () {
  25952. /**
  25953. * Instantiates an AssetContainer.
  25954. * @param scene The scene the AssetContainer belongs to.
  25955. */
  25956. function AssetContainer(scene) {
  25957. // Objects
  25958. /**
  25959. * Cameras populated in the container.
  25960. */
  25961. this.cameras = new Array();
  25962. /**
  25963. * Lights populated in the container.
  25964. */
  25965. this.lights = new Array();
  25966. /**
  25967. * Meshes populated in the container.
  25968. */
  25969. this.meshes = new Array();
  25970. /**
  25971. * Skeletons populated in the container.
  25972. */
  25973. this.skeletons = new Array();
  25974. /**
  25975. * ParticleSystems populated in the container.
  25976. */
  25977. this.particleSystems = new Array();
  25978. /**
  25979. * Animations populated in the container.
  25980. */
  25981. this.animations = new Array();
  25982. /**
  25983. * MultiMaterials populated in the container.
  25984. */
  25985. this.multiMaterials = new Array();
  25986. /**
  25987. * Materials populated in the container.
  25988. */
  25989. this.materials = new Array();
  25990. /**
  25991. * MorphTargetManagers populated in the container.
  25992. */
  25993. this.morphTargetManagers = new Array();
  25994. /**
  25995. * Geometries populated in the container.
  25996. */
  25997. this.geometries = new Array();
  25998. /**
  25999. * TransformNodes populated in the container.
  26000. */
  26001. this.transformNodes = new Array();
  26002. /**
  26003. * LensFlareSystems populated in the container.
  26004. */
  26005. this.lensFlareSystems = new Array();
  26006. /**
  26007. * ShadowGenerators populated in the container.
  26008. */
  26009. this.shadowGenerators = new Array();
  26010. /**
  26011. * ActionManagers populated in the container.
  26012. */
  26013. this.actionManagers = new Array();
  26014. /**
  26015. * Sounds populated in the container.
  26016. */
  26017. this.sounds = new Array();
  26018. this.scene = scene;
  26019. }
  26020. /**
  26021. * Adds all the assets from the container to the scene.
  26022. */
  26023. AssetContainer.prototype.addAllToScene = function () {
  26024. var _this = this;
  26025. this.cameras.forEach(function (o) {
  26026. _this.scene.addCamera(o);
  26027. });
  26028. this.lights.forEach(function (o) {
  26029. _this.scene.addLight(o);
  26030. });
  26031. this.meshes.forEach(function (o) {
  26032. _this.scene.addMesh(o);
  26033. });
  26034. this.skeletons.forEach(function (o) {
  26035. _this.scene.addSkeleton(o);
  26036. });
  26037. this.particleSystems.forEach(function (o) {
  26038. _this.scene.addParticleSystem(o);
  26039. });
  26040. this.animations.forEach(function (o) {
  26041. _this.scene.addAnimation(o);
  26042. });
  26043. this.multiMaterials.forEach(function (o) {
  26044. _this.scene.addMultiMaterial(o);
  26045. });
  26046. this.materials.forEach(function (o) {
  26047. _this.scene.addMaterial(o);
  26048. });
  26049. this.morphTargetManagers.forEach(function (o) {
  26050. _this.scene.addMorphTargetManager(o);
  26051. });
  26052. this.geometries.forEach(function (o) {
  26053. _this.scene.addGeometry(o);
  26054. });
  26055. this.transformNodes.forEach(function (o) {
  26056. _this.scene.addTransformNode(o);
  26057. });
  26058. this.lensFlareSystems.forEach(function (o) {
  26059. _this.scene.addLensFlareSystem(o);
  26060. });
  26061. this.actionManagers.forEach(function (o) {
  26062. _this.scene.addActionManager(o);
  26063. });
  26064. this.sounds.forEach(function (o) {
  26065. o.play();
  26066. o.autoplay = true;
  26067. _this.scene.mainSoundTrack.AddSound(o);
  26068. });
  26069. };
  26070. /**
  26071. * Removes all the assets in the container from the scene
  26072. */
  26073. AssetContainer.prototype.removeAllFromScene = function () {
  26074. var _this = this;
  26075. this.cameras.forEach(function (o) {
  26076. _this.scene.removeCamera(o);
  26077. });
  26078. this.lights.forEach(function (o) {
  26079. _this.scene.removeLight(o);
  26080. });
  26081. this.meshes.forEach(function (o) {
  26082. _this.scene.removeMesh(o);
  26083. });
  26084. this.skeletons.forEach(function (o) {
  26085. _this.scene.removeSkeleton(o);
  26086. });
  26087. this.particleSystems.forEach(function (o) {
  26088. _this.scene.removeParticleSystem(o);
  26089. });
  26090. this.animations.forEach(function (o) {
  26091. _this.scene.removeAnimation(o);
  26092. });
  26093. this.multiMaterials.forEach(function (o) {
  26094. _this.scene.removeMultiMaterial(o);
  26095. });
  26096. this.materials.forEach(function (o) {
  26097. _this.scene.removeMaterial(o);
  26098. });
  26099. this.morphTargetManagers.forEach(function (o) {
  26100. _this.scene.removeMorphTargetManager(o);
  26101. });
  26102. this.geometries.forEach(function (o) {
  26103. _this.scene.removeGeometry(o);
  26104. });
  26105. this.transformNodes.forEach(function (o) {
  26106. _this.scene.removeTransformNode(o);
  26107. });
  26108. this.lensFlareSystems.forEach(function (o) {
  26109. _this.scene.removeLensFlareSystem(o);
  26110. });
  26111. this.actionManagers.forEach(function (o) {
  26112. _this.scene.removeActionManager(o);
  26113. });
  26114. this.sounds.forEach(function (o) {
  26115. o.stop();
  26116. o.autoplay = false;
  26117. _this.scene.mainSoundTrack.RemoveSound(o);
  26118. });
  26119. };
  26120. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  26121. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  26122. var asset = sourceAssets_1[_i];
  26123. var move = true;
  26124. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  26125. var keepAsset = keepAssets_1[_a];
  26126. if (asset === keepAsset) {
  26127. move = false;
  26128. break;
  26129. }
  26130. }
  26131. if (move) {
  26132. targetAssets.push(asset);
  26133. }
  26134. }
  26135. };
  26136. /**
  26137. * Removes all the assets contained in the scene and adds them to the container.
  26138. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  26139. */
  26140. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  26141. if (keepAssets === undefined) {
  26142. keepAssets = new KeepAssets();
  26143. }
  26144. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  26145. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  26146. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  26147. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  26148. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  26149. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  26150. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  26151. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  26152. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  26153. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  26154. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  26155. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  26156. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  26157. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  26158. this.removeAllFromScene();
  26159. };
  26160. return AssetContainer;
  26161. }());
  26162. BABYLON.AssetContainer = AssetContainer;
  26163. })(BABYLON || (BABYLON = {}));
  26164. //# sourceMappingURL=babylon.assetContainer.js.map
  26165. "use strict";
  26166. var BABYLON;
  26167. (function (BABYLON) {
  26168. var Buffer = /** @class */ (function () {
  26169. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  26170. if (instanced === void 0) { instanced = false; }
  26171. if (engine instanceof BABYLON.Mesh) {
  26172. this._engine = engine.getScene().getEngine();
  26173. }
  26174. else {
  26175. this._engine = engine;
  26176. }
  26177. this._updatable = updatable;
  26178. this._instanced = instanced;
  26179. this._data = data;
  26180. this._strideSize = stride;
  26181. if (!postponeInternalCreation) {
  26182. this.create();
  26183. }
  26184. }
  26185. /**
  26186. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  26187. * @param kind defines the vertex buffer kind (position, normal, etc.)
  26188. * @param offset defines offset in the buffer (0 by default)
  26189. * @param size defines the size in floats of attributes (position is 3 for instance)
  26190. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  26191. * @param instanced defines if the vertex buffer contains indexed data
  26192. * @returns the new vertex buffer
  26193. */
  26194. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced) {
  26195. // a lot of these parameters are ignored as they are overriden by the buffer
  26196. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, instanced === undefined ? this._instanced : instanced, offset, size);
  26197. };
  26198. // Properties
  26199. Buffer.prototype.isUpdatable = function () {
  26200. return this._updatable;
  26201. };
  26202. Buffer.prototype.getData = function () {
  26203. return this._data;
  26204. };
  26205. Buffer.prototype.getBuffer = function () {
  26206. return this._buffer;
  26207. };
  26208. Buffer.prototype.getStrideSize = function () {
  26209. return this._strideSize;
  26210. };
  26211. // public getIsInstanced(): boolean {
  26212. // return this._instanced;
  26213. // }
  26214. // public get instanceDivisor(): number {
  26215. // return this._instanceDivisor;
  26216. // }
  26217. // public set instanceDivisor(value: number) {
  26218. // this._instanceDivisor = value;
  26219. // if (value == 0) {
  26220. // this._instanced = false;
  26221. // } else {
  26222. // this._instanced = true;
  26223. // }
  26224. // }
  26225. // Methods
  26226. Buffer.prototype.create = function (data) {
  26227. if (data === void 0) { data = null; }
  26228. if (!data && this._buffer) {
  26229. return; // nothing to do
  26230. }
  26231. data = data || this._data;
  26232. if (!data) {
  26233. return;
  26234. }
  26235. if (!this._buffer) {
  26236. if (this._updatable) {
  26237. this._buffer = this._engine.createDynamicVertexBuffer(data);
  26238. this._data = data;
  26239. }
  26240. else {
  26241. this._buffer = this._engine.createVertexBuffer(data);
  26242. }
  26243. }
  26244. else if (this._updatable) {
  26245. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  26246. this._data = data;
  26247. }
  26248. };
  26249. Buffer.prototype._rebuild = function () {
  26250. this._buffer = null;
  26251. this.create(this._data);
  26252. };
  26253. Buffer.prototype.update = function (data) {
  26254. this.create(data);
  26255. };
  26256. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  26257. if (!this._buffer) {
  26258. return;
  26259. }
  26260. if (this._updatable) {
  26261. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  26262. this._data = null;
  26263. }
  26264. };
  26265. Buffer.prototype.dispose = function () {
  26266. if (!this._buffer) {
  26267. return;
  26268. }
  26269. if (this._engine._releaseBuffer(this._buffer)) {
  26270. this._buffer = null;
  26271. }
  26272. };
  26273. return Buffer;
  26274. }());
  26275. BABYLON.Buffer = Buffer;
  26276. })(BABYLON || (BABYLON = {}));
  26277. //# sourceMappingURL=babylon.buffer.js.map
  26278. "use strict";
  26279. var BABYLON;
  26280. (function (BABYLON) {
  26281. var VertexBuffer = /** @class */ (function () {
  26282. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  26283. if (data instanceof BABYLON.Buffer) {
  26284. if (!stride) {
  26285. stride = data.getStrideSize();
  26286. }
  26287. this._buffer = data;
  26288. this._ownsBuffer = false;
  26289. }
  26290. else {
  26291. if (!stride) {
  26292. stride = VertexBuffer.DeduceStride(kind);
  26293. }
  26294. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  26295. this._ownsBuffer = true;
  26296. }
  26297. this._stride = stride;
  26298. this._instanced = instanced !== undefined ? instanced : false;
  26299. this._instanceDivisor = instanced ? 1 : 0;
  26300. this._offset = offset ? offset : 0;
  26301. this._size = size ? size : stride;
  26302. this._kind = kind;
  26303. }
  26304. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  26305. /**
  26306. * Gets or sets the instance divisor when in instanced mode
  26307. */
  26308. get: function () {
  26309. return this._instanceDivisor;
  26310. },
  26311. set: function (value) {
  26312. this._instanceDivisor = value;
  26313. if (value == 0) {
  26314. this._instanced = false;
  26315. }
  26316. else {
  26317. this._instanced = true;
  26318. }
  26319. },
  26320. enumerable: true,
  26321. configurable: true
  26322. });
  26323. VertexBuffer.prototype._rebuild = function () {
  26324. if (!this._buffer) {
  26325. return;
  26326. }
  26327. this._buffer._rebuild();
  26328. };
  26329. /**
  26330. * Returns the kind of the VertexBuffer (string).
  26331. */
  26332. VertexBuffer.prototype.getKind = function () {
  26333. return this._kind;
  26334. };
  26335. // Properties
  26336. /**
  26337. * Boolean : is the VertexBuffer updatable ?
  26338. */
  26339. VertexBuffer.prototype.isUpdatable = function () {
  26340. return this._buffer.isUpdatable();
  26341. };
  26342. /**
  26343. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  26344. */
  26345. VertexBuffer.prototype.getData = function () {
  26346. return this._buffer.getData();
  26347. };
  26348. /**
  26349. * Returns the WebGLBuffer associated to the VertexBuffer.
  26350. */
  26351. VertexBuffer.prototype.getBuffer = function () {
  26352. return this._buffer.getBuffer();
  26353. };
  26354. /**
  26355. * Returns the stride of the VertexBuffer (integer).
  26356. */
  26357. VertexBuffer.prototype.getStrideSize = function () {
  26358. return this._stride;
  26359. };
  26360. /**
  26361. * Returns the offset (integer).
  26362. */
  26363. VertexBuffer.prototype.getOffset = function () {
  26364. return this._offset;
  26365. };
  26366. /**
  26367. * Returns the VertexBuffer total size (integer).
  26368. */
  26369. VertexBuffer.prototype.getSize = function () {
  26370. return this._size;
  26371. };
  26372. /**
  26373. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  26374. */
  26375. VertexBuffer.prototype.getIsInstanced = function () {
  26376. return this._instanced;
  26377. };
  26378. /**
  26379. * Returns the instancing divisor, zero for non-instanced (integer).
  26380. */
  26381. VertexBuffer.prototype.getInstanceDivisor = function () {
  26382. return this._instanceDivisor;
  26383. };
  26384. // Methods
  26385. /**
  26386. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  26387. * Returns the created WebGLBuffer.
  26388. */
  26389. VertexBuffer.prototype.create = function (data) {
  26390. return this._buffer.create(data);
  26391. };
  26392. /**
  26393. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  26394. * This function will create a new buffer if the current one is not updatable
  26395. * Returns the updated WebGLBuffer.
  26396. */
  26397. VertexBuffer.prototype.update = function (data) {
  26398. return this._buffer.update(data);
  26399. };
  26400. /**
  26401. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  26402. * Returns the directly updated WebGLBuffer.
  26403. */
  26404. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  26405. return this._buffer.updateDirectly(data, offset);
  26406. };
  26407. /**
  26408. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  26409. */
  26410. VertexBuffer.prototype.dispose = function () {
  26411. if (this._ownsBuffer) {
  26412. this._buffer.dispose();
  26413. }
  26414. };
  26415. Object.defineProperty(VertexBuffer, "PositionKind", {
  26416. get: function () {
  26417. return VertexBuffer._PositionKind;
  26418. },
  26419. enumerable: true,
  26420. configurable: true
  26421. });
  26422. Object.defineProperty(VertexBuffer, "NormalKind", {
  26423. get: function () {
  26424. return VertexBuffer._NormalKind;
  26425. },
  26426. enumerable: true,
  26427. configurable: true
  26428. });
  26429. Object.defineProperty(VertexBuffer, "TangentKind", {
  26430. get: function () {
  26431. return VertexBuffer._TangentKind;
  26432. },
  26433. enumerable: true,
  26434. configurable: true
  26435. });
  26436. Object.defineProperty(VertexBuffer, "UVKind", {
  26437. get: function () {
  26438. return VertexBuffer._UVKind;
  26439. },
  26440. enumerable: true,
  26441. configurable: true
  26442. });
  26443. Object.defineProperty(VertexBuffer, "UV2Kind", {
  26444. get: function () {
  26445. return VertexBuffer._UV2Kind;
  26446. },
  26447. enumerable: true,
  26448. configurable: true
  26449. });
  26450. Object.defineProperty(VertexBuffer, "UV3Kind", {
  26451. get: function () {
  26452. return VertexBuffer._UV3Kind;
  26453. },
  26454. enumerable: true,
  26455. configurable: true
  26456. });
  26457. Object.defineProperty(VertexBuffer, "UV4Kind", {
  26458. get: function () {
  26459. return VertexBuffer._UV4Kind;
  26460. },
  26461. enumerable: true,
  26462. configurable: true
  26463. });
  26464. Object.defineProperty(VertexBuffer, "UV5Kind", {
  26465. get: function () {
  26466. return VertexBuffer._UV5Kind;
  26467. },
  26468. enumerable: true,
  26469. configurable: true
  26470. });
  26471. Object.defineProperty(VertexBuffer, "UV6Kind", {
  26472. get: function () {
  26473. return VertexBuffer._UV6Kind;
  26474. },
  26475. enumerable: true,
  26476. configurable: true
  26477. });
  26478. Object.defineProperty(VertexBuffer, "ColorKind", {
  26479. get: function () {
  26480. return VertexBuffer._ColorKind;
  26481. },
  26482. enumerable: true,
  26483. configurable: true
  26484. });
  26485. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  26486. get: function () {
  26487. return VertexBuffer._MatricesIndicesKind;
  26488. },
  26489. enumerable: true,
  26490. configurable: true
  26491. });
  26492. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  26493. get: function () {
  26494. return VertexBuffer._MatricesWeightsKind;
  26495. },
  26496. enumerable: true,
  26497. configurable: true
  26498. });
  26499. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  26500. get: function () {
  26501. return VertexBuffer._MatricesIndicesExtraKind;
  26502. },
  26503. enumerable: true,
  26504. configurable: true
  26505. });
  26506. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  26507. get: function () {
  26508. return VertexBuffer._MatricesWeightsExtraKind;
  26509. },
  26510. enumerable: true,
  26511. configurable: true
  26512. });
  26513. /**
  26514. * Deduces the stride given a kind.
  26515. * @param kind The kind string to deduce
  26516. * @returns The deduced stride
  26517. */
  26518. VertexBuffer.DeduceStride = function (kind) {
  26519. switch (kind) {
  26520. case VertexBuffer.UVKind:
  26521. case VertexBuffer.UV2Kind:
  26522. case VertexBuffer.UV3Kind:
  26523. case VertexBuffer.UV4Kind:
  26524. case VertexBuffer.UV5Kind:
  26525. case VertexBuffer.UV6Kind:
  26526. return 2;
  26527. case VertexBuffer.NormalKind:
  26528. case VertexBuffer.PositionKind:
  26529. return 3;
  26530. case VertexBuffer.ColorKind:
  26531. case VertexBuffer.MatricesIndicesKind:
  26532. case VertexBuffer.MatricesIndicesExtraKind:
  26533. case VertexBuffer.MatricesWeightsKind:
  26534. case VertexBuffer.MatricesWeightsExtraKind:
  26535. case VertexBuffer.TangentKind:
  26536. return 4;
  26537. default:
  26538. throw new Error("Invalid kind '" + kind + "'");
  26539. }
  26540. };
  26541. // Enums
  26542. VertexBuffer._PositionKind = "position";
  26543. VertexBuffer._NormalKind = "normal";
  26544. VertexBuffer._TangentKind = "tangent";
  26545. VertexBuffer._UVKind = "uv";
  26546. VertexBuffer._UV2Kind = "uv2";
  26547. VertexBuffer._UV3Kind = "uv3";
  26548. VertexBuffer._UV4Kind = "uv4";
  26549. VertexBuffer._UV5Kind = "uv5";
  26550. VertexBuffer._UV6Kind = "uv6";
  26551. VertexBuffer._ColorKind = "color";
  26552. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  26553. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  26554. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  26555. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  26556. return VertexBuffer;
  26557. }());
  26558. BABYLON.VertexBuffer = VertexBuffer;
  26559. })(BABYLON || (BABYLON = {}));
  26560. //# sourceMappingURL=babylon.vertexBuffer.js.map
  26561. "use strict";
  26562. var BABYLON;
  26563. (function (BABYLON) {
  26564. /**
  26565. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  26566. */
  26567. var DummyInternalTextureTracker = /** @class */ (function () {
  26568. function DummyInternalTextureTracker() {
  26569. /**
  26570. * Gets or set the previous tracker in the list
  26571. */
  26572. this.previous = null;
  26573. /**
  26574. * Gets or set the next tracker in the list
  26575. */
  26576. this.next = null;
  26577. }
  26578. return DummyInternalTextureTracker;
  26579. }());
  26580. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  26581. })(BABYLON || (BABYLON = {}));
  26582. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  26583. "use strict";
  26584. var BABYLON;
  26585. (function (BABYLON) {
  26586. /**
  26587. * Class used to store data associated with WebGL texture data for the engine
  26588. * This class should not be used directly
  26589. */
  26590. var InternalTexture = /** @class */ (function () {
  26591. /**
  26592. * Creates a new InternalTexture
  26593. * @param engine defines the engine to use
  26594. * @param dataSource defines the type of data that will be used
  26595. */
  26596. function InternalTexture(engine, dataSource) {
  26597. /**
  26598. * Observable called when the texture is loaded
  26599. */
  26600. this.onLoadedObservable = new BABYLON.Observable();
  26601. /**
  26602. * Gets or set the previous tracker in the list
  26603. */
  26604. this.previous = null;
  26605. /**
  26606. * Gets or set the next tracker in the list
  26607. */
  26608. this.next = null;
  26609. // Private
  26610. /** @ignore */
  26611. this._initialSlot = -1;
  26612. /** @ignore */
  26613. this._designatedSlot = -1;
  26614. /** @ignore */
  26615. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  26616. /** @ignore */
  26617. this._comparisonFunction = 0;
  26618. /** @ignore */
  26619. this._references = 1;
  26620. this._engine = engine;
  26621. this._dataSource = dataSource;
  26622. this._webGLTexture = engine._createTexture();
  26623. }
  26624. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  26625. /**
  26626. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  26627. */
  26628. get: function () {
  26629. return this._dataSource;
  26630. },
  26631. enumerable: true,
  26632. configurable: true
  26633. });
  26634. /**
  26635. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  26636. */
  26637. InternalTexture.prototype.incrementReferences = function () {
  26638. this._references++;
  26639. };
  26640. /**
  26641. * Change the size of the texture (not the size of the content)
  26642. * @param width defines the new width
  26643. * @param height defines the new height
  26644. * @param depth defines the new depth (1 by default)
  26645. */
  26646. InternalTexture.prototype.updateSize = function (width, height, depth) {
  26647. if (depth === void 0) { depth = 1; }
  26648. this.width = width;
  26649. this.height = height;
  26650. this.depth = depth;
  26651. this.baseWidth = width;
  26652. this.baseHeight = height;
  26653. this.baseDepth = depth;
  26654. this._size = width * height * depth;
  26655. };
  26656. /** @ignore */
  26657. InternalTexture.prototype._rebuild = function () {
  26658. var _this = this;
  26659. var proxy;
  26660. this.isReady = false;
  26661. this._cachedCoordinatesMode = null;
  26662. this._cachedWrapU = null;
  26663. this._cachedWrapV = null;
  26664. this._cachedAnisotropicFilteringLevel = null;
  26665. switch (this._dataSource) {
  26666. case InternalTexture.DATASOURCE_TEMP:
  26667. return;
  26668. case InternalTexture.DATASOURCE_URL:
  26669. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  26670. _this.isReady = true;
  26671. }, null, this._buffer, undefined, this.format);
  26672. proxy._swapAndDie(this);
  26673. return;
  26674. case InternalTexture.DATASOURCE_RAW:
  26675. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26676. proxy._swapAndDie(this);
  26677. this.isReady = true;
  26678. return;
  26679. case InternalTexture.DATASOURCE_RAW3D:
  26680. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26681. proxy._swapAndDie(this);
  26682. this.isReady = true;
  26683. return;
  26684. case InternalTexture.DATASOURCE_DYNAMIC:
  26685. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  26686. proxy._swapAndDie(this);
  26687. // The engine will make sure to update content so no need to flag it as isReady = true
  26688. return;
  26689. case InternalTexture.DATASOURCE_RENDERTARGET:
  26690. var options = new BABYLON.RenderTargetCreationOptions();
  26691. options.generateDepthBuffer = this._generateDepthBuffer;
  26692. options.generateMipMaps = this.generateMipMaps;
  26693. options.generateStencilBuffer = this._generateStencilBuffer;
  26694. options.samplingMode = this.samplingMode;
  26695. options.type = this.type;
  26696. if (this.isCube) {
  26697. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  26698. }
  26699. else {
  26700. var size = {
  26701. width: this.width,
  26702. height: this.height
  26703. };
  26704. proxy = this._engine.createRenderTargetTexture(size, options);
  26705. }
  26706. proxy._swapAndDie(this);
  26707. this.isReady = true;
  26708. return;
  26709. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  26710. var depthTextureOptions = {
  26711. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  26712. comparisonFunction: this._comparisonFunction,
  26713. generateStencil: this._generateStencilBuffer,
  26714. isCube: this.isCube
  26715. };
  26716. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  26717. proxy._swapAndDie(this);
  26718. this.isReady = true;
  26719. return;
  26720. case InternalTexture.DATASOURCE_CUBE:
  26721. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  26722. _this.isReady = true;
  26723. }, null, this.format, this._extension);
  26724. proxy._swapAndDie(this);
  26725. return;
  26726. case InternalTexture.DATASOURCE_CUBERAW:
  26727. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  26728. proxy._swapAndDie(this);
  26729. this.isReady = true;
  26730. return;
  26731. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  26732. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  26733. if (proxy) {
  26734. proxy._swapAndDie(_this);
  26735. }
  26736. _this.isReady = true;
  26737. }, null, this.format, this._extension);
  26738. return;
  26739. }
  26740. };
  26741. InternalTexture.prototype._swapAndDie = function (target) {
  26742. target._webGLTexture = this._webGLTexture;
  26743. if (this._framebuffer) {
  26744. target._framebuffer = this._framebuffer;
  26745. }
  26746. if (this._depthStencilBuffer) {
  26747. target._depthStencilBuffer = this._depthStencilBuffer;
  26748. }
  26749. if (this._lodTextureHigh) {
  26750. if (target._lodTextureHigh) {
  26751. target._lodTextureHigh.dispose();
  26752. }
  26753. target._lodTextureHigh = this._lodTextureHigh;
  26754. }
  26755. if (this._lodTextureMid) {
  26756. if (target._lodTextureMid) {
  26757. target._lodTextureMid.dispose();
  26758. }
  26759. target._lodTextureMid = this._lodTextureMid;
  26760. }
  26761. if (this._lodTextureLow) {
  26762. if (target._lodTextureLow) {
  26763. target._lodTextureLow.dispose();
  26764. }
  26765. target._lodTextureLow = this._lodTextureLow;
  26766. }
  26767. var cache = this._engine.getLoadedTexturesCache();
  26768. var index = cache.indexOf(this);
  26769. if (index !== -1) {
  26770. cache.splice(index, 1);
  26771. }
  26772. };
  26773. /**
  26774. * Dispose the current allocated resources
  26775. */
  26776. InternalTexture.prototype.dispose = function () {
  26777. if (!this._webGLTexture) {
  26778. return;
  26779. }
  26780. this._references--;
  26781. if (this._references === 0) {
  26782. this._engine._releaseTexture(this);
  26783. this._webGLTexture = null;
  26784. this.previous = null;
  26785. this.next = null;
  26786. }
  26787. };
  26788. /**
  26789. * The source of the texture data is unknown
  26790. */
  26791. InternalTexture.DATASOURCE_UNKNOWN = 0;
  26792. /**
  26793. * Texture data comes from an URL
  26794. */
  26795. InternalTexture.DATASOURCE_URL = 1;
  26796. /**
  26797. * Texture data is only used for temporary storage
  26798. */
  26799. InternalTexture.DATASOURCE_TEMP = 2;
  26800. /**
  26801. * Texture data comes from raw data (ArrayBuffer)
  26802. */
  26803. InternalTexture.DATASOURCE_RAW = 3;
  26804. /**
  26805. * Texture content is dynamic (video or dynamic texture)
  26806. */
  26807. InternalTexture.DATASOURCE_DYNAMIC = 4;
  26808. /**
  26809. * Texture content is generated by rendering to it
  26810. */
  26811. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  26812. /**
  26813. * Texture content is part of a multi render target process
  26814. */
  26815. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  26816. /**
  26817. * Texture data comes from a cube data file
  26818. */
  26819. InternalTexture.DATASOURCE_CUBE = 7;
  26820. /**
  26821. * Texture data comes from a raw cube data
  26822. */
  26823. InternalTexture.DATASOURCE_CUBERAW = 8;
  26824. /**
  26825. * Texture data come from a prefiltered cube data file
  26826. */
  26827. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  26828. /**
  26829. * Texture content is raw 3D data
  26830. */
  26831. InternalTexture.DATASOURCE_RAW3D = 10;
  26832. /**
  26833. * Texture content is a depth texture
  26834. */
  26835. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  26836. return InternalTexture;
  26837. }());
  26838. BABYLON.InternalTexture = InternalTexture;
  26839. })(BABYLON || (BABYLON = {}));
  26840. //# sourceMappingURL=babylon.internalTexture.js.map
  26841. "use strict";
  26842. var BABYLON;
  26843. (function (BABYLON) {
  26844. var BaseTexture = /** @class */ (function () {
  26845. function BaseTexture(scene) {
  26846. this._hasAlpha = false;
  26847. this.getAlphaFromRGB = false;
  26848. this.level = 1;
  26849. this.coordinatesIndex = 0;
  26850. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  26851. /**
  26852. * | Value | Type | Description |
  26853. * | ----- | ------------------ | ----------- |
  26854. * | 0 | CLAMP_ADDRESSMODE | |
  26855. * | 1 | WRAP_ADDRESSMODE | |
  26856. * | 2 | MIRROR_ADDRESSMODE | |
  26857. */
  26858. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  26859. /**
  26860. * | Value | Type | Description |
  26861. * | ----- | ------------------ | ----------- |
  26862. * | 0 | CLAMP_ADDRESSMODE | |
  26863. * | 1 | WRAP_ADDRESSMODE | |
  26864. * | 2 | MIRROR_ADDRESSMODE | |
  26865. */
  26866. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  26867. /**
  26868. * | Value | Type | Description |
  26869. * | ----- | ------------------ | ----------- |
  26870. * | 0 | CLAMP_ADDRESSMODE | |
  26871. * | 1 | WRAP_ADDRESSMODE | |
  26872. * | 2 | MIRROR_ADDRESSMODE | |
  26873. */
  26874. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  26875. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  26876. this.isCube = false;
  26877. this.is3D = false;
  26878. this.gammaSpace = true;
  26879. this.invertZ = false;
  26880. this.lodLevelInAlpha = false;
  26881. this.lodGenerationOffset = 0.0;
  26882. this.lodGenerationScale = 0.8;
  26883. this.isRenderTarget = false;
  26884. this.animations = new Array();
  26885. /**
  26886. * An event triggered when the texture is disposed.
  26887. * @type {BABYLON.Observable}
  26888. */
  26889. this.onDisposeObservable = new BABYLON.Observable();
  26890. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  26891. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  26892. if (this._scene) {
  26893. this._scene.textures.push(this);
  26894. }
  26895. this._uid = null;
  26896. }
  26897. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  26898. get: function () {
  26899. return this._hasAlpha;
  26900. },
  26901. set: function (value) {
  26902. if (this._hasAlpha === value) {
  26903. return;
  26904. }
  26905. this._hasAlpha = value;
  26906. if (this._scene) {
  26907. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  26908. }
  26909. },
  26910. enumerable: true,
  26911. configurable: true
  26912. });
  26913. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  26914. get: function () {
  26915. return this._coordinatesMode;
  26916. },
  26917. /**
  26918. * How a texture is mapped.
  26919. *
  26920. * | Value | Type | Description |
  26921. * | ----- | ----------------------------------- | ----------- |
  26922. * | 0 | EXPLICIT_MODE | |
  26923. * | 1 | SPHERICAL_MODE | |
  26924. * | 2 | PLANAR_MODE | |
  26925. * | 3 | CUBIC_MODE | |
  26926. * | 4 | PROJECTION_MODE | |
  26927. * | 5 | SKYBOX_MODE | |
  26928. * | 6 | INVCUBIC_MODE | |
  26929. * | 7 | EQUIRECTANGULAR_MODE | |
  26930. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  26931. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  26932. */
  26933. set: function (value) {
  26934. if (this._coordinatesMode === value) {
  26935. return;
  26936. }
  26937. this._coordinatesMode = value;
  26938. if (this._scene) {
  26939. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  26940. }
  26941. },
  26942. enumerable: true,
  26943. configurable: true
  26944. });
  26945. Object.defineProperty(BaseTexture.prototype, "uid", {
  26946. get: function () {
  26947. if (!this._uid) {
  26948. this._uid = BABYLON.Tools.RandomId();
  26949. }
  26950. return this._uid;
  26951. },
  26952. enumerable: true,
  26953. configurable: true
  26954. });
  26955. BaseTexture.prototype.toString = function () {
  26956. return this.name;
  26957. };
  26958. BaseTexture.prototype.getClassName = function () {
  26959. return "BaseTexture";
  26960. };
  26961. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  26962. set: function (callback) {
  26963. if (this._onDisposeObserver) {
  26964. this.onDisposeObservable.remove(this._onDisposeObserver);
  26965. }
  26966. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26967. },
  26968. enumerable: true,
  26969. configurable: true
  26970. });
  26971. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  26972. get: function () {
  26973. return true;
  26974. },
  26975. enumerable: true,
  26976. configurable: true
  26977. });
  26978. BaseTexture.prototype.getScene = function () {
  26979. return this._scene;
  26980. };
  26981. BaseTexture.prototype.getTextureMatrix = function () {
  26982. return BABYLON.Matrix.IdentityReadOnly;
  26983. };
  26984. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  26985. return BABYLON.Matrix.IdentityReadOnly;
  26986. };
  26987. BaseTexture.prototype.getInternalTexture = function () {
  26988. return this._texture;
  26989. };
  26990. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  26991. return !this.isBlocking || this.isReady();
  26992. };
  26993. BaseTexture.prototype.isReady = function () {
  26994. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  26995. this.delayLoad();
  26996. return false;
  26997. }
  26998. if (this._texture) {
  26999. return this._texture.isReady;
  27000. }
  27001. return false;
  27002. };
  27003. BaseTexture.prototype.getSize = function () {
  27004. if (this._texture && this._texture.width) {
  27005. return new BABYLON.Size(this._texture.width, this._texture.height);
  27006. }
  27007. if (this._texture && this._texture._size) {
  27008. return new BABYLON.Size(this._texture._size, this._texture._size);
  27009. }
  27010. return BABYLON.Size.Zero();
  27011. };
  27012. BaseTexture.prototype.getBaseSize = function () {
  27013. if (!this.isReady() || !this._texture)
  27014. return BABYLON.Size.Zero();
  27015. if (this._texture._size) {
  27016. return new BABYLON.Size(this._texture._size, this._texture._size);
  27017. }
  27018. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  27019. };
  27020. BaseTexture.prototype.scale = function (ratio) {
  27021. };
  27022. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  27023. get: function () {
  27024. return false;
  27025. },
  27026. enumerable: true,
  27027. configurable: true
  27028. });
  27029. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  27030. if (!this._scene) {
  27031. return null;
  27032. }
  27033. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  27034. for (var index = 0; index < texturesCache.length; index++) {
  27035. var texturesCacheEntry = texturesCache[index];
  27036. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  27037. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  27038. texturesCacheEntry.incrementReferences();
  27039. return texturesCacheEntry;
  27040. }
  27041. }
  27042. }
  27043. return null;
  27044. };
  27045. BaseTexture.prototype._rebuild = function () {
  27046. };
  27047. BaseTexture.prototype.delayLoad = function () {
  27048. };
  27049. BaseTexture.prototype.clone = function () {
  27050. return null;
  27051. };
  27052. Object.defineProperty(BaseTexture.prototype, "textureType", {
  27053. get: function () {
  27054. if (!this._texture) {
  27055. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  27056. }
  27057. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  27058. },
  27059. enumerable: true,
  27060. configurable: true
  27061. });
  27062. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  27063. get: function () {
  27064. if (!this._texture) {
  27065. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  27066. }
  27067. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  27068. },
  27069. enumerable: true,
  27070. configurable: true
  27071. });
  27072. BaseTexture.prototype.readPixels = function (faceIndex) {
  27073. if (faceIndex === void 0) { faceIndex = 0; }
  27074. if (!this._texture) {
  27075. return null;
  27076. }
  27077. var size = this.getSize();
  27078. var scene = this.getScene();
  27079. if (!scene) {
  27080. return null;
  27081. }
  27082. var engine = scene.getEngine();
  27083. if (this._texture.isCube) {
  27084. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  27085. }
  27086. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  27087. };
  27088. BaseTexture.prototype.releaseInternalTexture = function () {
  27089. if (this._texture) {
  27090. this._texture.dispose();
  27091. this._texture = null;
  27092. }
  27093. };
  27094. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  27095. get: function () {
  27096. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  27097. return null;
  27098. }
  27099. if (!this._texture._sphericalPolynomial) {
  27100. this._texture._sphericalPolynomial =
  27101. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  27102. }
  27103. return this._texture._sphericalPolynomial;
  27104. },
  27105. set: function (value) {
  27106. if (this._texture) {
  27107. this._texture._sphericalPolynomial = value;
  27108. }
  27109. },
  27110. enumerable: true,
  27111. configurable: true
  27112. });
  27113. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  27114. get: function () {
  27115. if (this._texture) {
  27116. return this._texture._lodTextureHigh;
  27117. }
  27118. return null;
  27119. },
  27120. enumerable: true,
  27121. configurable: true
  27122. });
  27123. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  27124. get: function () {
  27125. if (this._texture) {
  27126. return this._texture._lodTextureMid;
  27127. }
  27128. return null;
  27129. },
  27130. enumerable: true,
  27131. configurable: true
  27132. });
  27133. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  27134. get: function () {
  27135. if (this._texture) {
  27136. return this._texture._lodTextureLow;
  27137. }
  27138. return null;
  27139. },
  27140. enumerable: true,
  27141. configurable: true
  27142. });
  27143. BaseTexture.prototype.dispose = function () {
  27144. if (!this._scene) {
  27145. return;
  27146. }
  27147. // Animations
  27148. this._scene.stopAnimation(this);
  27149. // Remove from scene
  27150. this._scene._removePendingData(this);
  27151. var index = this._scene.textures.indexOf(this);
  27152. if (index >= 0) {
  27153. this._scene.textures.splice(index, 1);
  27154. }
  27155. if (this._texture === undefined) {
  27156. return;
  27157. }
  27158. // Release
  27159. this.releaseInternalTexture();
  27160. // Callback
  27161. this.onDisposeObservable.notifyObservers(this);
  27162. this.onDisposeObservable.clear();
  27163. };
  27164. BaseTexture.prototype.serialize = function () {
  27165. if (!this.name) {
  27166. return null;
  27167. }
  27168. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  27169. // Animations
  27170. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  27171. return serializationObject;
  27172. };
  27173. BaseTexture.WhenAllReady = function (textures, callback) {
  27174. var numRemaining = textures.length;
  27175. if (numRemaining === 0) {
  27176. callback();
  27177. return;
  27178. }
  27179. var _loop_1 = function () {
  27180. texture = textures[i];
  27181. if (texture.isReady()) {
  27182. if (--numRemaining === 0) {
  27183. callback();
  27184. }
  27185. }
  27186. else {
  27187. onLoadObservable = texture.onLoadObservable;
  27188. var onLoadCallback_1 = function () {
  27189. onLoadObservable.removeCallback(onLoadCallback_1);
  27190. if (--numRemaining === 0) {
  27191. callback();
  27192. }
  27193. };
  27194. onLoadObservable.add(onLoadCallback_1);
  27195. }
  27196. };
  27197. var texture, onLoadObservable;
  27198. for (var i = 0; i < textures.length; i++) {
  27199. _loop_1();
  27200. }
  27201. };
  27202. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  27203. __decorate([
  27204. BABYLON.serialize()
  27205. ], BaseTexture.prototype, "name", void 0);
  27206. __decorate([
  27207. BABYLON.serialize("hasAlpha")
  27208. ], BaseTexture.prototype, "_hasAlpha", void 0);
  27209. __decorate([
  27210. BABYLON.serialize()
  27211. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  27212. __decorate([
  27213. BABYLON.serialize()
  27214. ], BaseTexture.prototype, "level", void 0);
  27215. __decorate([
  27216. BABYLON.serialize()
  27217. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  27218. __decorate([
  27219. BABYLON.serialize("coordinatesMode")
  27220. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  27221. __decorate([
  27222. BABYLON.serialize()
  27223. ], BaseTexture.prototype, "wrapU", void 0);
  27224. __decorate([
  27225. BABYLON.serialize()
  27226. ], BaseTexture.prototype, "wrapV", void 0);
  27227. __decorate([
  27228. BABYLON.serialize()
  27229. ], BaseTexture.prototype, "wrapR", void 0);
  27230. __decorate([
  27231. BABYLON.serialize()
  27232. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  27233. __decorate([
  27234. BABYLON.serialize()
  27235. ], BaseTexture.prototype, "isCube", void 0);
  27236. __decorate([
  27237. BABYLON.serialize()
  27238. ], BaseTexture.prototype, "is3D", void 0);
  27239. __decorate([
  27240. BABYLON.serialize()
  27241. ], BaseTexture.prototype, "gammaSpace", void 0);
  27242. __decorate([
  27243. BABYLON.serialize()
  27244. ], BaseTexture.prototype, "invertZ", void 0);
  27245. __decorate([
  27246. BABYLON.serialize()
  27247. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  27248. __decorate([
  27249. BABYLON.serialize()
  27250. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  27251. __decorate([
  27252. BABYLON.serialize()
  27253. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  27254. __decorate([
  27255. BABYLON.serialize()
  27256. ], BaseTexture.prototype, "isRenderTarget", void 0);
  27257. return BaseTexture;
  27258. }());
  27259. BABYLON.BaseTexture = BaseTexture;
  27260. })(BABYLON || (BABYLON = {}));
  27261. //# sourceMappingURL=babylon.baseTexture.js.map
  27262. "use strict";
  27263. var BABYLON;
  27264. (function (BABYLON) {
  27265. var Texture = /** @class */ (function (_super) {
  27266. __extends(Texture, _super);
  27267. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  27268. if (noMipmap === void 0) { noMipmap = false; }
  27269. if (invertY === void 0) { invertY = true; }
  27270. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27271. if (onLoad === void 0) { onLoad = null; }
  27272. if (onError === void 0) { onError = null; }
  27273. if (buffer === void 0) { buffer = null; }
  27274. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27275. var _this = _super.call(this, scene) || this;
  27276. _this.uOffset = 0;
  27277. _this.vOffset = 0;
  27278. _this.uScale = 1.0;
  27279. _this.vScale = 1.0;
  27280. _this.uAng = 0;
  27281. _this.vAng = 0;
  27282. _this.wAng = 0;
  27283. _this._isBlocking = true;
  27284. _this.name = url || "";
  27285. _this.url = url;
  27286. _this._noMipmap = noMipmap;
  27287. _this._invertY = invertY;
  27288. _this._samplingMode = samplingMode;
  27289. _this._buffer = buffer;
  27290. _this._deleteBuffer = deleteBuffer;
  27291. if (format) {
  27292. _this._format = format;
  27293. }
  27294. scene = _this.getScene();
  27295. if (!scene) {
  27296. return _this;
  27297. }
  27298. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  27299. var load = function () {
  27300. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  27301. _this.onLoadObservable.notifyObservers(_this);
  27302. }
  27303. if (onLoad) {
  27304. onLoad();
  27305. }
  27306. if (!_this.isBlocking && scene) {
  27307. scene.resetCachedMaterial();
  27308. }
  27309. };
  27310. if (!_this.url) {
  27311. _this._delayedOnLoad = load;
  27312. _this._delayedOnError = onError;
  27313. return _this;
  27314. }
  27315. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  27316. if (!_this._texture) {
  27317. if (!scene.useDelayedTextureLoading) {
  27318. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  27319. if (deleteBuffer) {
  27320. delete _this._buffer;
  27321. }
  27322. }
  27323. else {
  27324. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27325. _this._delayedOnLoad = load;
  27326. _this._delayedOnError = onError;
  27327. }
  27328. }
  27329. else {
  27330. if (_this._texture.isReady) {
  27331. BABYLON.Tools.SetImmediate(function () { return load(); });
  27332. }
  27333. else {
  27334. _this._texture.onLoadedObservable.add(load);
  27335. }
  27336. }
  27337. return _this;
  27338. }
  27339. Object.defineProperty(Texture.prototype, "noMipmap", {
  27340. get: function () {
  27341. return this._noMipmap;
  27342. },
  27343. enumerable: true,
  27344. configurable: true
  27345. });
  27346. Object.defineProperty(Texture.prototype, "isBlocking", {
  27347. get: function () {
  27348. return this._isBlocking;
  27349. },
  27350. set: function (value) {
  27351. this._isBlocking = value;
  27352. },
  27353. enumerable: true,
  27354. configurable: true
  27355. });
  27356. Object.defineProperty(Texture.prototype, "samplingMode", {
  27357. get: function () {
  27358. return this._samplingMode;
  27359. },
  27360. enumerable: true,
  27361. configurable: true
  27362. });
  27363. Texture.prototype.updateURL = function (url) {
  27364. this.url = url;
  27365. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  27366. this.delayLoad();
  27367. };
  27368. Texture.prototype.delayLoad = function () {
  27369. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  27370. return;
  27371. }
  27372. var scene = this.getScene();
  27373. if (!scene) {
  27374. return;
  27375. }
  27376. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  27377. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  27378. if (!this._texture) {
  27379. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  27380. if (this._deleteBuffer) {
  27381. delete this._buffer;
  27382. }
  27383. }
  27384. else {
  27385. if (this._delayedOnLoad) {
  27386. if (this._texture.isReady) {
  27387. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  27388. }
  27389. else {
  27390. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  27391. }
  27392. }
  27393. }
  27394. this._delayedOnLoad = null;
  27395. this._delayedOnError = null;
  27396. };
  27397. Texture.prototype.updateSamplingMode = function (samplingMode) {
  27398. if (!this._texture) {
  27399. return;
  27400. }
  27401. var scene = this.getScene();
  27402. if (!scene) {
  27403. return;
  27404. }
  27405. this._samplingMode = samplingMode;
  27406. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  27407. };
  27408. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  27409. x *= this.uScale;
  27410. y *= this.vScale;
  27411. x -= 0.5 * this.uScale;
  27412. y -= 0.5 * this.vScale;
  27413. z -= 0.5;
  27414. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  27415. t.x += 0.5 * this.uScale + this.uOffset;
  27416. t.y += 0.5 * this.vScale + this.vOffset;
  27417. t.z += 0.5;
  27418. };
  27419. Texture.prototype.getTextureMatrix = function () {
  27420. var _this = this;
  27421. if (this.uOffset === this._cachedUOffset &&
  27422. this.vOffset === this._cachedVOffset &&
  27423. this.uScale === this._cachedUScale &&
  27424. this.vScale === this._cachedVScale &&
  27425. this.uAng === this._cachedUAng &&
  27426. this.vAng === this._cachedVAng &&
  27427. this.wAng === this._cachedWAng) {
  27428. return this._cachedTextureMatrix;
  27429. }
  27430. this._cachedUOffset = this.uOffset;
  27431. this._cachedVOffset = this.vOffset;
  27432. this._cachedUScale = this.uScale;
  27433. this._cachedVScale = this.vScale;
  27434. this._cachedUAng = this.uAng;
  27435. this._cachedVAng = this.vAng;
  27436. this._cachedWAng = this.wAng;
  27437. if (!this._cachedTextureMatrix) {
  27438. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27439. this._rowGenerationMatrix = new BABYLON.Matrix();
  27440. this._t0 = BABYLON.Vector3.Zero();
  27441. this._t1 = BABYLON.Vector3.Zero();
  27442. this._t2 = BABYLON.Vector3.Zero();
  27443. }
  27444. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  27445. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  27446. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  27447. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  27448. this._t1.subtractInPlace(this._t0);
  27449. this._t2.subtractInPlace(this._t0);
  27450. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27451. this._cachedTextureMatrix.m[0] = this._t1.x;
  27452. this._cachedTextureMatrix.m[1] = this._t1.y;
  27453. this._cachedTextureMatrix.m[2] = this._t1.z;
  27454. this._cachedTextureMatrix.m[4] = this._t2.x;
  27455. this._cachedTextureMatrix.m[5] = this._t2.y;
  27456. this._cachedTextureMatrix.m[6] = this._t2.z;
  27457. this._cachedTextureMatrix.m[8] = this._t0.x;
  27458. this._cachedTextureMatrix.m[9] = this._t0.y;
  27459. this._cachedTextureMatrix.m[10] = this._t0.z;
  27460. var scene = this.getScene();
  27461. if (!scene) {
  27462. return this._cachedTextureMatrix;
  27463. }
  27464. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27465. return mat.hasTexture(_this);
  27466. });
  27467. return this._cachedTextureMatrix;
  27468. };
  27469. Texture.prototype.getReflectionTextureMatrix = function () {
  27470. var _this = this;
  27471. var scene = this.getScene();
  27472. if (!scene) {
  27473. return this._cachedTextureMatrix;
  27474. }
  27475. if (this.uOffset === this._cachedUOffset &&
  27476. this.vOffset === this._cachedVOffset &&
  27477. this.uScale === this._cachedUScale &&
  27478. this.vScale === this._cachedVScale &&
  27479. this.coordinatesMode === this._cachedCoordinatesMode) {
  27480. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  27481. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  27482. return this._cachedTextureMatrix;
  27483. }
  27484. }
  27485. else {
  27486. return this._cachedTextureMatrix;
  27487. }
  27488. }
  27489. if (!this._cachedTextureMatrix) {
  27490. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  27491. }
  27492. if (!this._projectionModeMatrix) {
  27493. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  27494. }
  27495. this._cachedUOffset = this.uOffset;
  27496. this._cachedVOffset = this.vOffset;
  27497. this._cachedUScale = this.uScale;
  27498. this._cachedVScale = this.vScale;
  27499. this._cachedCoordinatesMode = this.coordinatesMode;
  27500. switch (this.coordinatesMode) {
  27501. case Texture.PLANAR_MODE:
  27502. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27503. this._cachedTextureMatrix[0] = this.uScale;
  27504. this._cachedTextureMatrix[5] = this.vScale;
  27505. this._cachedTextureMatrix[12] = this.uOffset;
  27506. this._cachedTextureMatrix[13] = this.vOffset;
  27507. break;
  27508. case Texture.PROJECTION_MODE:
  27509. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  27510. this._projectionModeMatrix.m[0] = 0.5;
  27511. this._projectionModeMatrix.m[5] = -0.5;
  27512. this._projectionModeMatrix.m[10] = 0.0;
  27513. this._projectionModeMatrix.m[12] = 0.5;
  27514. this._projectionModeMatrix.m[13] = 0.5;
  27515. this._projectionModeMatrix.m[14] = 1.0;
  27516. this._projectionModeMatrix.m[15] = 1.0;
  27517. var projectionMatrix = scene.getProjectionMatrix();
  27518. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  27519. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  27520. break;
  27521. default:
  27522. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  27523. break;
  27524. }
  27525. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  27526. return (mat.getActiveTextures().indexOf(_this) !== -1);
  27527. });
  27528. return this._cachedTextureMatrix;
  27529. };
  27530. Texture.prototype.clone = function () {
  27531. var _this = this;
  27532. return BABYLON.SerializationHelper.Clone(function () {
  27533. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  27534. }, this);
  27535. };
  27536. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  27537. get: function () {
  27538. if (!this._onLoadObservable) {
  27539. this._onLoadObservable = new BABYLON.Observable();
  27540. }
  27541. return this._onLoadObservable;
  27542. },
  27543. enumerable: true,
  27544. configurable: true
  27545. });
  27546. Texture.prototype.serialize = function () {
  27547. var serializationObject = _super.prototype.serialize.call(this);
  27548. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  27549. serializationObject.base64String = this._buffer;
  27550. serializationObject.name = serializationObject.name.replace("data:", "");
  27551. }
  27552. return serializationObject;
  27553. };
  27554. Texture.prototype.getClassName = function () {
  27555. return "Texture";
  27556. };
  27557. Texture.prototype.dispose = function () {
  27558. _super.prototype.dispose.call(this);
  27559. if (this.onLoadObservable) {
  27560. this.onLoadObservable.clear();
  27561. this._onLoadObservable = null;
  27562. }
  27563. this._delayedOnLoad = null;
  27564. this._delayedOnError = null;
  27565. };
  27566. // Statics
  27567. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27568. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27569. if (onLoad === void 0) { onLoad = null; }
  27570. if (onError === void 0) { onError = null; }
  27571. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27572. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  27573. };
  27574. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  27575. if (parsedTexture.customType) {
  27576. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  27577. // Update Sampling Mode
  27578. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  27579. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  27580. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  27581. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  27582. }
  27583. }
  27584. return parsedCustomTexture;
  27585. }
  27586. if (parsedTexture.isCube) {
  27587. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  27588. }
  27589. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  27590. return null;
  27591. }
  27592. var texture = BABYLON.SerializationHelper.Parse(function () {
  27593. var generateMipMaps = true;
  27594. if (parsedTexture.noMipmap) {
  27595. generateMipMaps = false;
  27596. }
  27597. if (parsedTexture.mirrorPlane) {
  27598. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27599. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  27600. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  27601. return mirrorTexture;
  27602. }
  27603. else if (parsedTexture.isRenderTarget) {
  27604. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  27605. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  27606. return renderTargetTexture;
  27607. }
  27608. else {
  27609. var texture;
  27610. if (parsedTexture.base64String) {
  27611. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  27612. }
  27613. else {
  27614. var url = rootUrl + parsedTexture.name;
  27615. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  27616. url = parsedTexture.url;
  27617. }
  27618. texture = new Texture(url, scene, !generateMipMaps);
  27619. }
  27620. return texture;
  27621. }
  27622. }, parsedTexture, scene);
  27623. // Update Sampling Mode
  27624. if (parsedTexture.samplingMode) {
  27625. var sampling = parsedTexture.samplingMode;
  27626. if (texture._samplingMode !== sampling) {
  27627. texture.updateSamplingMode(sampling);
  27628. }
  27629. }
  27630. // Animations
  27631. if (parsedTexture.animations) {
  27632. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  27633. var parsedAnimation = parsedTexture.animations[animationIndex];
  27634. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  27635. }
  27636. }
  27637. return texture;
  27638. };
  27639. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  27640. if (deleteBuffer === void 0) { deleteBuffer = false; }
  27641. if (noMipmap === void 0) { noMipmap = false; }
  27642. if (invertY === void 0) { invertY = true; }
  27643. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  27644. if (onLoad === void 0) { onLoad = null; }
  27645. if (onError === void 0) { onError = null; }
  27646. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  27647. if (name.substr(0, 5) !== "data:") {
  27648. name = "data:" + name;
  27649. }
  27650. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  27651. };
  27652. // Constants
  27653. Texture.NEAREST_SAMPLINGMODE = 1;
  27654. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  27655. Texture.BILINEAR_SAMPLINGMODE = 2;
  27656. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  27657. Texture.TRILINEAR_SAMPLINGMODE = 3;
  27658. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  27659. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  27660. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  27661. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  27662. Texture.NEAREST_LINEAR = 7;
  27663. Texture.NEAREST_NEAREST = 8;
  27664. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  27665. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  27666. Texture.LINEAR_LINEAR = 11;
  27667. Texture.LINEAR_NEAREST = 12;
  27668. Texture.EXPLICIT_MODE = 0;
  27669. Texture.SPHERICAL_MODE = 1;
  27670. Texture.PLANAR_MODE = 2;
  27671. Texture.CUBIC_MODE = 3;
  27672. Texture.PROJECTION_MODE = 4;
  27673. Texture.SKYBOX_MODE = 5;
  27674. Texture.INVCUBIC_MODE = 6;
  27675. Texture.EQUIRECTANGULAR_MODE = 7;
  27676. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  27677. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  27678. Texture.CLAMP_ADDRESSMODE = 0;
  27679. Texture.WRAP_ADDRESSMODE = 1;
  27680. Texture.MIRROR_ADDRESSMODE = 2;
  27681. /**
  27682. * 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
  27683. */
  27684. Texture.UseSerializedUrlIfAny = false;
  27685. __decorate([
  27686. BABYLON.serialize()
  27687. ], Texture.prototype, "url", void 0);
  27688. __decorate([
  27689. BABYLON.serialize()
  27690. ], Texture.prototype, "uOffset", void 0);
  27691. __decorate([
  27692. BABYLON.serialize()
  27693. ], Texture.prototype, "vOffset", void 0);
  27694. __decorate([
  27695. BABYLON.serialize()
  27696. ], Texture.prototype, "uScale", void 0);
  27697. __decorate([
  27698. BABYLON.serialize()
  27699. ], Texture.prototype, "vScale", void 0);
  27700. __decorate([
  27701. BABYLON.serialize()
  27702. ], Texture.prototype, "uAng", void 0);
  27703. __decorate([
  27704. BABYLON.serialize()
  27705. ], Texture.prototype, "vAng", void 0);
  27706. __decorate([
  27707. BABYLON.serialize()
  27708. ], Texture.prototype, "wAng", void 0);
  27709. __decorate([
  27710. BABYLON.serialize()
  27711. ], Texture.prototype, "isBlocking", null);
  27712. return Texture;
  27713. }(BABYLON.BaseTexture));
  27714. BABYLON.Texture = Texture;
  27715. })(BABYLON || (BABYLON = {}));
  27716. //# sourceMappingURL=babylon.texture.js.map
  27717. "use strict";
  27718. var BABYLON;
  27719. (function (BABYLON) {
  27720. var _InstancesBatch = /** @class */ (function () {
  27721. function _InstancesBatch() {
  27722. this.mustReturn = false;
  27723. this.visibleInstances = new Array();
  27724. this.renderSelf = new Array();
  27725. }
  27726. return _InstancesBatch;
  27727. }());
  27728. BABYLON._InstancesBatch = _InstancesBatch;
  27729. var Mesh = /** @class */ (function (_super) {
  27730. __extends(Mesh, _super);
  27731. /**
  27732. * @constructor
  27733. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  27734. * @param {Scene} scene The scene to add this mesh to.
  27735. * @param {Node} parent The parent of this mesh, if it has one
  27736. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  27737. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  27738. * When false, achieved by calling a clone(), also passing False.
  27739. * This will make creation of children, recursive.
  27740. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  27741. */
  27742. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  27743. if (scene === void 0) { scene = null; }
  27744. if (parent === void 0) { parent = null; }
  27745. if (source === void 0) { source = null; }
  27746. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  27747. var _this = _super.call(this, name, scene) || this;
  27748. // Events
  27749. /**
  27750. * An event triggered before rendering the mesh
  27751. * @type {BABYLON.Observable}
  27752. */
  27753. _this.onBeforeRenderObservable = new BABYLON.Observable();
  27754. /**
  27755. * An event triggered after rendering the mesh
  27756. * @type {BABYLON.Observable}
  27757. */
  27758. _this.onAfterRenderObservable = new BABYLON.Observable();
  27759. /**
  27760. * An event triggered before drawing the mesh
  27761. * @type {BABYLON.Observable}
  27762. */
  27763. _this.onBeforeDrawObservable = new BABYLON.Observable();
  27764. // Members
  27765. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  27766. _this.instances = new Array();
  27767. _this._LODLevels = new Array();
  27768. _this._visibleInstances = {};
  27769. _this._renderIdForInstances = new Array();
  27770. _this._batchCache = new _InstancesBatch();
  27771. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  27772. // Use by builder only to know what orientation were the mesh build in.
  27773. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  27774. _this.overrideMaterialSideOrientation = null;
  27775. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  27776. // Will be used to save a source mesh reference, If any
  27777. _this._source = null;
  27778. scene = _this.getScene();
  27779. if (source) {
  27780. // Source mesh
  27781. _this._source = source;
  27782. // Geometry
  27783. if (source._geometry) {
  27784. source._geometry.applyToMesh(_this);
  27785. }
  27786. // Deep copy
  27787. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId", "source", "metadata"], ["_poseMatrix", "_source"]);
  27788. // Metadata
  27789. if (source.metadata && source.metadata.clone) {
  27790. _this.metadata = source.metadata.clone();
  27791. }
  27792. else {
  27793. _this.metadata = source.metadata;
  27794. }
  27795. // Tags
  27796. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  27797. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  27798. }
  27799. // Parent
  27800. _this.parent = source.parent;
  27801. // Pivot
  27802. _this.setPivotMatrix(source.getPivotMatrix());
  27803. _this.id = name + "." + source.id;
  27804. // Material
  27805. _this.material = source.material;
  27806. var index;
  27807. if (!doNotCloneChildren) {
  27808. // Children
  27809. var directDescendants = source.getDescendants(true);
  27810. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  27811. var child = directDescendants[index_1];
  27812. if (child.clone) {
  27813. child.clone(name + "." + child.name, _this);
  27814. }
  27815. }
  27816. }
  27817. // Physics clone
  27818. var physicsEngine = _this.getScene().getPhysicsEngine();
  27819. if (clonePhysicsImpostor && physicsEngine) {
  27820. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  27821. if (impostor) {
  27822. _this.physicsImpostor = impostor.clone(_this);
  27823. }
  27824. }
  27825. // Particles
  27826. for (index = 0; index < scene.particleSystems.length; index++) {
  27827. var system = scene.particleSystems[index];
  27828. if (system.emitter === source) {
  27829. system.clone(system.name, _this);
  27830. }
  27831. }
  27832. _this.computeWorldMatrix(true);
  27833. }
  27834. // Parent
  27835. if (parent !== null) {
  27836. _this.parent = parent;
  27837. }
  27838. return _this;
  27839. }
  27840. Object.defineProperty(Mesh, "FRONTSIDE", {
  27841. /**
  27842. * Mesh side orientation : usually the external or front surface
  27843. */
  27844. get: function () {
  27845. return Mesh._FRONTSIDE;
  27846. },
  27847. enumerable: true,
  27848. configurable: true
  27849. });
  27850. Object.defineProperty(Mesh, "BACKSIDE", {
  27851. /**
  27852. * Mesh side orientation : usually the internal or back surface
  27853. */
  27854. get: function () {
  27855. return Mesh._BACKSIDE;
  27856. },
  27857. enumerable: true,
  27858. configurable: true
  27859. });
  27860. Object.defineProperty(Mesh, "DOUBLESIDE", {
  27861. /**
  27862. * Mesh side orientation : both internal and external or front and back surfaces
  27863. */
  27864. get: function () {
  27865. return Mesh._DOUBLESIDE;
  27866. },
  27867. enumerable: true,
  27868. configurable: true
  27869. });
  27870. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  27871. /**
  27872. * Mesh side orientation : by default, `FRONTSIDE`
  27873. */
  27874. get: function () {
  27875. return Mesh._DEFAULTSIDE;
  27876. },
  27877. enumerable: true,
  27878. configurable: true
  27879. });
  27880. Object.defineProperty(Mesh, "NO_CAP", {
  27881. /**
  27882. * Mesh cap setting : no cap
  27883. */
  27884. get: function () {
  27885. return Mesh._NO_CAP;
  27886. },
  27887. enumerable: true,
  27888. configurable: true
  27889. });
  27890. Object.defineProperty(Mesh, "CAP_START", {
  27891. /**
  27892. * Mesh cap setting : one cap at the beginning of the mesh
  27893. */
  27894. get: function () {
  27895. return Mesh._CAP_START;
  27896. },
  27897. enumerable: true,
  27898. configurable: true
  27899. });
  27900. Object.defineProperty(Mesh, "CAP_END", {
  27901. /**
  27902. * Mesh cap setting : one cap at the end of the mesh
  27903. */
  27904. get: function () {
  27905. return Mesh._CAP_END;
  27906. },
  27907. enumerable: true,
  27908. configurable: true
  27909. });
  27910. Object.defineProperty(Mesh, "CAP_ALL", {
  27911. /**
  27912. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  27913. */
  27914. get: function () {
  27915. return Mesh._CAP_ALL;
  27916. },
  27917. enumerable: true,
  27918. configurable: true
  27919. });
  27920. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  27921. set: function (callback) {
  27922. if (this._onBeforeDrawObserver) {
  27923. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  27924. }
  27925. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  27926. },
  27927. enumerable: true,
  27928. configurable: true
  27929. });
  27930. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  27931. get: function () {
  27932. return this._morphTargetManager;
  27933. },
  27934. set: function (value) {
  27935. if (this._morphTargetManager === value) {
  27936. return;
  27937. }
  27938. this._morphTargetManager = value;
  27939. this._syncGeometryWithMorphTargetManager();
  27940. },
  27941. enumerable: true,
  27942. configurable: true
  27943. });
  27944. Object.defineProperty(Mesh.prototype, "source", {
  27945. get: function () {
  27946. return this._source;
  27947. },
  27948. enumerable: true,
  27949. configurable: true
  27950. });
  27951. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  27952. get: function () {
  27953. return this._unIndexed;
  27954. },
  27955. set: function (value) {
  27956. if (this._unIndexed !== value) {
  27957. this._unIndexed = value;
  27958. this._markSubMeshesAsAttributesDirty();
  27959. }
  27960. },
  27961. enumerable: true,
  27962. configurable: true
  27963. });
  27964. // Methods
  27965. /**
  27966. * Returns the string "Mesh".
  27967. */
  27968. Mesh.prototype.getClassName = function () {
  27969. return "Mesh";
  27970. };
  27971. /**
  27972. * Returns a string.
  27973. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27974. */
  27975. Mesh.prototype.toString = function (fullDetails) {
  27976. var ret = _super.prototype.toString.call(this, fullDetails);
  27977. ret += ", n vertices: " + this.getTotalVertices();
  27978. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  27979. if (this.animations) {
  27980. for (var i = 0; i < this.animations.length; i++) {
  27981. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  27982. }
  27983. }
  27984. if (fullDetails) {
  27985. if (this._geometry) {
  27986. var ib = this.getIndices();
  27987. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27988. if (vb && ib) {
  27989. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  27990. }
  27991. }
  27992. else {
  27993. ret += ", flat shading: UNKNOWN";
  27994. }
  27995. }
  27996. return ret;
  27997. };
  27998. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  27999. /**
  28000. * True if the mesh has some Levels Of Details (LOD).
  28001. * Returns a boolean.
  28002. */
  28003. get: function () {
  28004. return this._LODLevels.length > 0;
  28005. },
  28006. enumerable: true,
  28007. configurable: true
  28008. });
  28009. /**
  28010. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  28011. * @returns an array of {BABYLON.MeshLODLevel}
  28012. */
  28013. Mesh.prototype.getLODLevels = function () {
  28014. return this._LODLevels;
  28015. };
  28016. Mesh.prototype._sortLODLevels = function () {
  28017. this._LODLevels.sort(function (a, b) {
  28018. if (a.distance < b.distance) {
  28019. return 1;
  28020. }
  28021. if (a.distance > b.distance) {
  28022. return -1;
  28023. }
  28024. return 0;
  28025. });
  28026. };
  28027. /**
  28028. * Add a mesh as LOD level triggered at the given distance.
  28029. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28030. * @param {number} distance The distance from the center of the object to show this level
  28031. * @param {Mesh} mesh The mesh to be added as LOD level
  28032. * @return {Mesh} This mesh (for chaining)
  28033. */
  28034. Mesh.prototype.addLODLevel = function (distance, mesh) {
  28035. if (mesh && mesh._masterMesh) {
  28036. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  28037. return this;
  28038. }
  28039. var level = new BABYLON.MeshLODLevel(distance, mesh);
  28040. this._LODLevels.push(level);
  28041. if (mesh) {
  28042. mesh._masterMesh = this;
  28043. }
  28044. this._sortLODLevels();
  28045. return this;
  28046. };
  28047. /**
  28048. * Returns the LOD level mesh at the passed distance or null if not found.
  28049. * It is related to the method `addLODLevel(distance, mesh)`.
  28050. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28051. * Returns an object Mesh or `null`.
  28052. */
  28053. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  28054. for (var index = 0; index < this._LODLevels.length; index++) {
  28055. var level = this._LODLevels[index];
  28056. if (level.distance === distance) {
  28057. return level.mesh;
  28058. }
  28059. }
  28060. return null;
  28061. };
  28062. /**
  28063. * Remove a mesh from the LOD array
  28064. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28065. * @param {Mesh} mesh The mesh to be removed.
  28066. * @return {Mesh} This mesh (for chaining)
  28067. */
  28068. Mesh.prototype.removeLODLevel = function (mesh) {
  28069. for (var index = 0; index < this._LODLevels.length; index++) {
  28070. if (this._LODLevels[index].mesh === mesh) {
  28071. this._LODLevels.splice(index, 1);
  28072. if (mesh) {
  28073. mesh._masterMesh = null;
  28074. }
  28075. }
  28076. }
  28077. this._sortLODLevels();
  28078. return this;
  28079. };
  28080. /**
  28081. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  28082. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  28083. */
  28084. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  28085. if (!this._LODLevels || this._LODLevels.length === 0) {
  28086. return this;
  28087. }
  28088. var bSphere;
  28089. if (boundingSphere) {
  28090. bSphere = boundingSphere;
  28091. }
  28092. else {
  28093. var boundingInfo = this.getBoundingInfo();
  28094. bSphere = boundingInfo.boundingSphere;
  28095. }
  28096. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  28097. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  28098. if (this.onLODLevelSelection) {
  28099. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  28100. }
  28101. return this;
  28102. }
  28103. for (var index = 0; index < this._LODLevels.length; index++) {
  28104. var level = this._LODLevels[index];
  28105. if (level.distance < distanceToCamera) {
  28106. if (level.mesh) {
  28107. level.mesh._preActivate();
  28108. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  28109. }
  28110. if (this.onLODLevelSelection) {
  28111. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  28112. }
  28113. return level.mesh;
  28114. }
  28115. }
  28116. if (this.onLODLevelSelection) {
  28117. this.onLODLevelSelection(distanceToCamera, this, this);
  28118. }
  28119. return this;
  28120. };
  28121. Object.defineProperty(Mesh.prototype, "geometry", {
  28122. /**
  28123. * Returns the mesh internal Geometry object.
  28124. */
  28125. get: function () {
  28126. return this._geometry;
  28127. },
  28128. enumerable: true,
  28129. configurable: true
  28130. });
  28131. /**
  28132. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  28133. */
  28134. Mesh.prototype.getTotalVertices = function () {
  28135. if (this._geometry === null || this._geometry === undefined) {
  28136. return 0;
  28137. }
  28138. return this._geometry.getTotalVertices();
  28139. };
  28140. /**
  28141. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  28142. * 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.
  28143. * You can force the copy with forceCopy === true
  28144. * Returns null if the mesh has no geometry or no vertex buffer.
  28145. * Possible `kind` values :
  28146. * - BABYLON.VertexBuffer.PositionKind
  28147. * - BABYLON.VertexBuffer.UVKind
  28148. * - BABYLON.VertexBuffer.UV2Kind
  28149. * - BABYLON.VertexBuffer.UV3Kind
  28150. * - BABYLON.VertexBuffer.UV4Kind
  28151. * - BABYLON.VertexBuffer.UV5Kind
  28152. * - BABYLON.VertexBuffer.UV6Kind
  28153. * - BABYLON.VertexBuffer.ColorKind
  28154. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28155. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28156. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28157. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28158. */
  28159. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  28160. if (!this._geometry) {
  28161. return null;
  28162. }
  28163. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  28164. };
  28165. /**
  28166. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  28167. * Returns `null` if the mesh has no geometry.
  28168. * Possible `kind` values :
  28169. * - BABYLON.VertexBuffer.PositionKind
  28170. * - BABYLON.VertexBuffer.UVKind
  28171. * - BABYLON.VertexBuffer.UV2Kind
  28172. * - BABYLON.VertexBuffer.UV3Kind
  28173. * - BABYLON.VertexBuffer.UV4Kind
  28174. * - BABYLON.VertexBuffer.UV5Kind
  28175. * - BABYLON.VertexBuffer.UV6Kind
  28176. * - BABYLON.VertexBuffer.ColorKind
  28177. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28178. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28179. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28180. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28181. */
  28182. Mesh.prototype.getVertexBuffer = function (kind) {
  28183. if (!this._geometry) {
  28184. return null;
  28185. }
  28186. return this._geometry.getVertexBuffer(kind);
  28187. };
  28188. /**
  28189. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  28190. * Possible `kind` values :
  28191. * - BABYLON.VertexBuffer.PositionKind
  28192. * - BABYLON.VertexBuffer.UVKind
  28193. * - BABYLON.VertexBuffer.UV2Kind
  28194. * - BABYLON.VertexBuffer.UV3Kind
  28195. * - BABYLON.VertexBuffer.UV4Kind
  28196. * - BABYLON.VertexBuffer.UV5Kind
  28197. * - BABYLON.VertexBuffer.UV6Kind
  28198. * - BABYLON.VertexBuffer.ColorKind
  28199. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28200. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28201. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28202. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28203. */
  28204. Mesh.prototype.isVerticesDataPresent = function (kind) {
  28205. if (!this._geometry) {
  28206. if (this._delayInfo) {
  28207. return this._delayInfo.indexOf(kind) !== -1;
  28208. }
  28209. return false;
  28210. }
  28211. return this._geometry.isVerticesDataPresent(kind);
  28212. };
  28213. /**
  28214. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  28215. * Possible `kind` values :
  28216. * - BABYLON.VertexBuffer.PositionKind
  28217. * - BABYLON.VertexBuffer.UVKind
  28218. * - BABYLON.VertexBuffer.UV2Kind
  28219. * - BABYLON.VertexBuffer.UV3Kind
  28220. * - BABYLON.VertexBuffer.UV4Kind
  28221. * - BABYLON.VertexBuffer.UV5Kind
  28222. * - BABYLON.VertexBuffer.UV6Kind
  28223. * - BABYLON.VertexBuffer.ColorKind
  28224. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28225. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28226. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28227. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28228. */
  28229. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  28230. if (!this._geometry) {
  28231. if (this._delayInfo) {
  28232. return this._delayInfo.indexOf(kind) !== -1;
  28233. }
  28234. return false;
  28235. }
  28236. return this._geometry.isVertexBufferUpdatable(kind);
  28237. };
  28238. /**
  28239. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  28240. * Possible `kind` values :
  28241. * - BABYLON.VertexBuffer.PositionKind
  28242. * - BABYLON.VertexBuffer.UVKind
  28243. * - BABYLON.VertexBuffer.UV2Kind
  28244. * - BABYLON.VertexBuffer.UV3Kind
  28245. * - BABYLON.VertexBuffer.UV4Kind
  28246. * - BABYLON.VertexBuffer.UV5Kind
  28247. * - BABYLON.VertexBuffer.UV6Kind
  28248. * - BABYLON.VertexBuffer.ColorKind
  28249. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28250. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28251. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28252. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28253. */
  28254. Mesh.prototype.getVerticesDataKinds = function () {
  28255. if (!this._geometry) {
  28256. var result = new Array();
  28257. if (this._delayInfo) {
  28258. this._delayInfo.forEach(function (kind, index, array) {
  28259. result.push(kind);
  28260. });
  28261. }
  28262. return result;
  28263. }
  28264. return this._geometry.getVerticesDataKinds();
  28265. };
  28266. /**
  28267. * Returns a positive integer : the total number of indices in this mesh geometry.
  28268. * Returns zero if the mesh has no geometry.
  28269. */
  28270. Mesh.prototype.getTotalIndices = function () {
  28271. if (!this._geometry) {
  28272. return 0;
  28273. }
  28274. return this._geometry.getTotalIndices();
  28275. };
  28276. /**
  28277. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  28278. * 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.
  28279. * Returns an empty array if the mesh has no geometry.
  28280. */
  28281. Mesh.prototype.getIndices = function (copyWhenShared) {
  28282. if (!this._geometry) {
  28283. return [];
  28284. }
  28285. return this._geometry.getIndices(copyWhenShared);
  28286. };
  28287. Object.defineProperty(Mesh.prototype, "isBlocked", {
  28288. get: function () {
  28289. return this._masterMesh !== null && this._masterMesh !== undefined;
  28290. },
  28291. enumerable: true,
  28292. configurable: true
  28293. });
  28294. /**
  28295. * Determine if the current mesh is ready to be rendered
  28296. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  28297. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  28298. * @returns true if all associated assets are ready (material, textures, shaders)
  28299. */
  28300. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  28301. if (completeCheck === void 0) { completeCheck = false; }
  28302. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  28303. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28304. return false;
  28305. }
  28306. if (!_super.prototype.isReady.call(this, completeCheck)) {
  28307. return false;
  28308. }
  28309. if (!this.subMeshes || this.subMeshes.length === 0) {
  28310. return true;
  28311. }
  28312. if (!completeCheck) {
  28313. return true;
  28314. }
  28315. var engine = this.getEngine();
  28316. var scene = this.getScene();
  28317. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  28318. this.computeWorldMatrix();
  28319. var mat = this.material || scene.defaultMaterial;
  28320. if (mat) {
  28321. if (mat.storeEffectOnSubMeshes) {
  28322. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  28323. var subMesh = _a[_i];
  28324. var effectiveMaterial = subMesh.getMaterial();
  28325. if (effectiveMaterial) {
  28326. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28327. return false;
  28328. }
  28329. }
  28330. }
  28331. }
  28332. else {
  28333. if (!mat.isReady(this, hardwareInstancedRendering)) {
  28334. return false;
  28335. }
  28336. }
  28337. }
  28338. // Shadows
  28339. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  28340. var light = _c[_b];
  28341. var generator = light.getShadowGenerator();
  28342. if (generator) {
  28343. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  28344. var subMesh = _e[_d];
  28345. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  28346. return false;
  28347. }
  28348. }
  28349. }
  28350. }
  28351. // LOD
  28352. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  28353. var lod = _g[_f];
  28354. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  28355. return false;
  28356. }
  28357. }
  28358. return true;
  28359. };
  28360. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  28361. /**
  28362. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  28363. * This property is pertinent only for updatable parametric shapes.
  28364. */
  28365. get: function () {
  28366. return this._areNormalsFrozen;
  28367. },
  28368. enumerable: true,
  28369. configurable: true
  28370. });
  28371. /**
  28372. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  28373. * It has no effect at all on other shapes.
  28374. * It prevents the mesh normals from being recomputed on next `positions` array update.
  28375. * Returns the Mesh.
  28376. */
  28377. Mesh.prototype.freezeNormals = function () {
  28378. this._areNormalsFrozen = true;
  28379. return this;
  28380. };
  28381. /**
  28382. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  28383. * It has no effect at all on other shapes.
  28384. * It reactivates the mesh normals computation if it was previously frozen.
  28385. * Returns the Mesh.
  28386. */
  28387. Mesh.prototype.unfreezeNormals = function () {
  28388. this._areNormalsFrozen = false;
  28389. return this;
  28390. };
  28391. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  28392. /**
  28393. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  28394. */
  28395. set: function (count) {
  28396. this._overridenInstanceCount = count;
  28397. },
  28398. enumerable: true,
  28399. configurable: true
  28400. });
  28401. // Methods
  28402. Mesh.prototype._preActivate = function () {
  28403. var sceneRenderId = this.getScene().getRenderId();
  28404. if (this._preActivateId === sceneRenderId) {
  28405. return this;
  28406. }
  28407. this._preActivateId = sceneRenderId;
  28408. this._visibleInstances = null;
  28409. return this;
  28410. };
  28411. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  28412. if (this._visibleInstances) {
  28413. this._visibleInstances.intermediateDefaultRenderId = renderId;
  28414. }
  28415. return this;
  28416. };
  28417. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  28418. if (!this._visibleInstances) {
  28419. this._visibleInstances = {};
  28420. this._visibleInstances.defaultRenderId = renderId;
  28421. this._visibleInstances.selfDefaultRenderId = this._renderId;
  28422. }
  28423. if (!this._visibleInstances[renderId]) {
  28424. this._visibleInstances[renderId] = new Array();
  28425. }
  28426. this._visibleInstances[renderId].push(instance);
  28427. return this;
  28428. };
  28429. /**
  28430. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  28431. * This means the mesh underlying bounding box and sphere are recomputed.
  28432. * Returns the Mesh.
  28433. */
  28434. Mesh.prototype.refreshBoundingInfo = function () {
  28435. return this._refreshBoundingInfo(false);
  28436. };
  28437. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  28438. if (this._boundingInfo && this._boundingInfo.isLocked) {
  28439. return this;
  28440. }
  28441. var data = this._getPositionData(applySkeleton);
  28442. if (data) {
  28443. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  28444. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  28445. }
  28446. if (this.subMeshes) {
  28447. for (var index = 0; index < this.subMeshes.length; index++) {
  28448. this.subMeshes[index].refreshBoundingInfo();
  28449. }
  28450. }
  28451. this._updateBoundingInfo();
  28452. return this;
  28453. };
  28454. Mesh.prototype._getPositionData = function (applySkeleton) {
  28455. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28456. if (data && applySkeleton && this.skeleton) {
  28457. data = BABYLON.Tools.Slice(data);
  28458. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  28459. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  28460. if (matricesWeightsData && matricesIndicesData) {
  28461. var needExtras = this.numBoneInfluencers > 4;
  28462. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  28463. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  28464. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  28465. var tempVector = BABYLON.Tmp.Vector3[0];
  28466. var finalMatrix = BABYLON.Tmp.Matrix[0];
  28467. var tempMatrix = BABYLON.Tmp.Matrix[1];
  28468. var matWeightIdx = 0;
  28469. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  28470. finalMatrix.reset();
  28471. var inf;
  28472. var weight;
  28473. for (inf = 0; inf < 4; inf++) {
  28474. weight = matricesWeightsData[matWeightIdx + inf];
  28475. if (weight <= 0)
  28476. break;
  28477. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28478. finalMatrix.addToSelf(tempMatrix);
  28479. }
  28480. if (needExtras) {
  28481. for (inf = 0; inf < 4; inf++) {
  28482. weight = matricesWeightsExtraData[matWeightIdx + inf];
  28483. if (weight <= 0)
  28484. break;
  28485. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  28486. finalMatrix.addToSelf(tempMatrix);
  28487. }
  28488. }
  28489. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  28490. tempVector.toArray(data, index);
  28491. }
  28492. }
  28493. }
  28494. return data;
  28495. };
  28496. Mesh.prototype._createGlobalSubMesh = function (force) {
  28497. var totalVertices = this.getTotalVertices();
  28498. if (!totalVertices || !this.getIndices()) {
  28499. return null;
  28500. }
  28501. // Check if we need to recreate the submeshes
  28502. if (this.subMeshes && this.subMeshes.length > 0) {
  28503. var ib = this.getIndices();
  28504. if (!ib) {
  28505. return null;
  28506. }
  28507. var totalIndices = ib.length;
  28508. var needToRecreate = false;
  28509. if (force) {
  28510. needToRecreate = true;
  28511. }
  28512. else {
  28513. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  28514. var submesh = _a[_i];
  28515. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  28516. needToRecreate = true;
  28517. break;
  28518. }
  28519. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  28520. needToRecreate = true;
  28521. break;
  28522. }
  28523. }
  28524. }
  28525. if (!needToRecreate) {
  28526. return this.subMeshes[0];
  28527. }
  28528. }
  28529. this.releaseSubMeshes();
  28530. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  28531. };
  28532. Mesh.prototype.subdivide = function (count) {
  28533. if (count < 1) {
  28534. return;
  28535. }
  28536. var totalIndices = this.getTotalIndices();
  28537. var subdivisionSize = (totalIndices / count) | 0;
  28538. var offset = 0;
  28539. // Ensure that subdivisionSize is a multiple of 3
  28540. while (subdivisionSize % 3 !== 0) {
  28541. subdivisionSize++;
  28542. }
  28543. this.releaseSubMeshes();
  28544. for (var index = 0; index < count; index++) {
  28545. if (offset >= totalIndices) {
  28546. break;
  28547. }
  28548. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  28549. offset += subdivisionSize;
  28550. }
  28551. this.synchronizeInstances();
  28552. };
  28553. /**
  28554. * Sets the vertex data of the mesh geometry for the requested `kind`.
  28555. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  28556. * The `data` are either a numeric array either a Float32Array.
  28557. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  28558. * 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).
  28559. * Note that a new underlying VertexBuffer object is created each call.
  28560. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  28561. *
  28562. * Possible `kind` values :
  28563. * - BABYLON.VertexBuffer.PositionKind
  28564. * - BABYLON.VertexBuffer.UVKind
  28565. * - BABYLON.VertexBuffer.UV2Kind
  28566. * - BABYLON.VertexBuffer.UV3Kind
  28567. * - BABYLON.VertexBuffer.UV4Kind
  28568. * - BABYLON.VertexBuffer.UV5Kind
  28569. * - BABYLON.VertexBuffer.UV6Kind
  28570. * - BABYLON.VertexBuffer.ColorKind
  28571. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28572. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28573. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28574. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28575. *
  28576. * Returns the Mesh.
  28577. */
  28578. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28579. if (updatable === void 0) { updatable = false; }
  28580. if (!this._geometry) {
  28581. var vertexData = new BABYLON.VertexData();
  28582. vertexData.set(data, kind);
  28583. var scene = this.getScene();
  28584. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28585. }
  28586. else {
  28587. this._geometry.setVerticesData(kind, data, updatable, stride);
  28588. }
  28589. return this;
  28590. };
  28591. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  28592. if (updatable === void 0) { updatable = true; }
  28593. var vb = this.getVertexBuffer(kind);
  28594. if (!vb || vb.isUpdatable() === updatable) {
  28595. return;
  28596. }
  28597. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  28598. };
  28599. /**
  28600. * Sets the mesh VertexBuffer.
  28601. * Returns the Mesh.
  28602. */
  28603. Mesh.prototype.setVerticesBuffer = function (buffer) {
  28604. if (!this._geometry) {
  28605. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  28606. }
  28607. this._geometry.setVerticesBuffer(buffer);
  28608. return this;
  28609. };
  28610. /**
  28611. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  28612. * If the mesh has no geometry, it is simply returned as it is.
  28613. * The `data` are either a numeric array either a Float32Array.
  28614. * No new underlying VertexBuffer object is created.
  28615. * 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.
  28616. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  28617. *
  28618. * Possible `kind` values :
  28619. * - BABYLON.VertexBuffer.PositionKind
  28620. * - BABYLON.VertexBuffer.UVKind
  28621. * - BABYLON.VertexBuffer.UV2Kind
  28622. * - BABYLON.VertexBuffer.UV3Kind
  28623. * - BABYLON.VertexBuffer.UV4Kind
  28624. * - BABYLON.VertexBuffer.UV5Kind
  28625. * - BABYLON.VertexBuffer.UV6Kind
  28626. * - BABYLON.VertexBuffer.ColorKind
  28627. * - BABYLON.VertexBuffer.MatricesIndicesKind
  28628. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  28629. * - BABYLON.VertexBuffer.MatricesWeightsKind
  28630. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  28631. *
  28632. * Returns the Mesh.
  28633. */
  28634. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  28635. if (!this._geometry) {
  28636. return this;
  28637. }
  28638. if (!makeItUnique) {
  28639. this._geometry.updateVerticesData(kind, data, updateExtends);
  28640. }
  28641. else {
  28642. this.makeGeometryUnique();
  28643. this.updateVerticesData(kind, data, updateExtends, false);
  28644. }
  28645. return this;
  28646. };
  28647. /**
  28648. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  28649. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  28650. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  28651. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  28652. * Returns the Mesh.
  28653. */
  28654. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  28655. if (computeNormals === void 0) { computeNormals = true; }
  28656. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28657. if (!positions) {
  28658. return this;
  28659. }
  28660. positionFunction(positions);
  28661. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  28662. if (computeNormals) {
  28663. var indices = this.getIndices();
  28664. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  28665. if (!normals) {
  28666. return this;
  28667. }
  28668. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  28669. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  28670. }
  28671. return this;
  28672. };
  28673. /**
  28674. * Creates a un-shared specific occurence of the geometry for the mesh.
  28675. * Returns the Mesh.
  28676. */
  28677. Mesh.prototype.makeGeometryUnique = function () {
  28678. if (!this._geometry) {
  28679. return this;
  28680. }
  28681. var oldGeometry = this._geometry;
  28682. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  28683. oldGeometry.releaseForMesh(this, true);
  28684. geometry.applyToMesh(this);
  28685. return this;
  28686. };
  28687. /**
  28688. * Sets the mesh indices.
  28689. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  28690. * Type is Uint16Array by default unless the mesh has more than 65536 vertices.
  28691. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  28692. * This method creates a new index buffer each call.
  28693. * Returns the Mesh.
  28694. */
  28695. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  28696. if (totalVertices === void 0) { totalVertices = null; }
  28697. if (updatable === void 0) { updatable = false; }
  28698. if (!this._geometry) {
  28699. var vertexData = new BABYLON.VertexData();
  28700. vertexData.indices = indices;
  28701. var scene = this.getScene();
  28702. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  28703. }
  28704. else {
  28705. this._geometry.setIndices(indices, totalVertices, updatable);
  28706. }
  28707. return this;
  28708. };
  28709. /**
  28710. * Update the current index buffer
  28711. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  28712. * Returns the Mesh.
  28713. */
  28714. Mesh.prototype.updateIndices = function (indices, offset) {
  28715. if (!this._geometry) {
  28716. return this;
  28717. }
  28718. this._geometry.updateIndices(indices, offset);
  28719. return this;
  28720. };
  28721. /**
  28722. * Invert the geometry to move from a right handed system to a left handed one.
  28723. * Returns the Mesh.
  28724. */
  28725. Mesh.prototype.toLeftHanded = function () {
  28726. if (!this._geometry) {
  28727. return this;
  28728. }
  28729. this._geometry.toLeftHanded();
  28730. return this;
  28731. };
  28732. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  28733. if (!this._geometry) {
  28734. return this;
  28735. }
  28736. var engine = this.getScene().getEngine();
  28737. // Wireframe
  28738. var indexToBind;
  28739. if (this._unIndexed) {
  28740. indexToBind = null;
  28741. }
  28742. else {
  28743. switch (fillMode) {
  28744. case BABYLON.Material.PointFillMode:
  28745. indexToBind = null;
  28746. break;
  28747. case BABYLON.Material.WireFrameFillMode:
  28748. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  28749. break;
  28750. default:
  28751. case BABYLON.Material.TriangleFillMode:
  28752. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  28753. break;
  28754. }
  28755. }
  28756. // VBOs
  28757. this._geometry._bind(effect, indexToBind);
  28758. return this;
  28759. };
  28760. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  28761. if (alternate === void 0) { alternate = false; }
  28762. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28763. return this;
  28764. }
  28765. this.onBeforeDrawObservable.notifyObservers(this);
  28766. var scene = this.getScene();
  28767. var engine = scene.getEngine();
  28768. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  28769. // or triangles as points
  28770. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  28771. }
  28772. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  28773. // Triangles as wireframe
  28774. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  28775. }
  28776. else {
  28777. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  28778. }
  28779. if (scene._isAlternateRenderingEnabled && !alternate) {
  28780. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  28781. if (!effect || !scene.activeCamera) {
  28782. return this;
  28783. }
  28784. scene._switchToAlternateCameraConfiguration(true);
  28785. this._effectiveMaterial.bindView(effect);
  28786. this._effectiveMaterial.bindViewProjection(effect);
  28787. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  28788. this._draw(subMesh, fillMode, instancesCount, true);
  28789. engine.setViewport(scene.activeCamera.viewport);
  28790. scene._switchToAlternateCameraConfiguration(false);
  28791. this._effectiveMaterial.bindView(effect);
  28792. this._effectiveMaterial.bindViewProjection(effect);
  28793. }
  28794. return this;
  28795. };
  28796. /**
  28797. * Registers for this mesh a javascript function called just before the rendering process.
  28798. * This function is passed the current mesh.
  28799. * Return the Mesh.
  28800. */
  28801. Mesh.prototype.registerBeforeRender = function (func) {
  28802. this.onBeforeRenderObservable.add(func);
  28803. return this;
  28804. };
  28805. /**
  28806. * Disposes a previously registered javascript function called before the rendering.
  28807. * This function is passed the current mesh.
  28808. * Returns the Mesh.
  28809. */
  28810. Mesh.prototype.unregisterBeforeRender = function (func) {
  28811. this.onBeforeRenderObservable.removeCallback(func);
  28812. return this;
  28813. };
  28814. /**
  28815. * Registers for this mesh a javascript function called just after the rendering is complete.
  28816. * This function is passed the current mesh.
  28817. * Returns the Mesh.
  28818. */
  28819. Mesh.prototype.registerAfterRender = function (func) {
  28820. this.onAfterRenderObservable.add(func);
  28821. return this;
  28822. };
  28823. /**
  28824. * Disposes a previously registered javascript function called after the rendering.
  28825. * This function is passed the current mesh.
  28826. * Return the Mesh.
  28827. */
  28828. Mesh.prototype.unregisterAfterRender = function (func) {
  28829. this.onAfterRenderObservable.removeCallback(func);
  28830. return this;
  28831. };
  28832. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  28833. var scene = this.getScene();
  28834. this._batchCache.mustReturn = false;
  28835. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  28836. this._batchCache.visibleInstances[subMeshId] = null;
  28837. if (this._visibleInstances) {
  28838. var currentRenderId = scene.getRenderId();
  28839. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  28840. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  28841. var selfRenderId = this._renderId;
  28842. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  28843. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  28844. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  28845. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  28846. }
  28847. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  28848. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  28849. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  28850. this._batchCache.mustReturn = true;
  28851. return this._batchCache;
  28852. }
  28853. if (currentRenderId !== selfRenderId) {
  28854. this._batchCache.renderSelf[subMeshId] = false;
  28855. }
  28856. }
  28857. this._renderIdForInstances[subMeshId] = currentRenderId;
  28858. }
  28859. return this._batchCache;
  28860. };
  28861. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  28862. var visibleInstances = batch.visibleInstances[subMesh._id];
  28863. if (!visibleInstances) {
  28864. return this;
  28865. }
  28866. var matricesCount = visibleInstances.length + 1;
  28867. var bufferSize = matricesCount * 16 * 4;
  28868. var currentInstancesBufferSize = this._instancesBufferSize;
  28869. var instancesBuffer = this._instancesBuffer;
  28870. while (this._instancesBufferSize < bufferSize) {
  28871. this._instancesBufferSize *= 2;
  28872. }
  28873. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  28874. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  28875. }
  28876. var offset = 0;
  28877. var instancesCount = 0;
  28878. var world = this.getWorldMatrix();
  28879. if (batch.renderSelf[subMesh._id]) {
  28880. world.copyToArray(this._instancesData, offset);
  28881. offset += 16;
  28882. instancesCount++;
  28883. }
  28884. if (visibleInstances) {
  28885. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  28886. var instance = visibleInstances[instanceIndex];
  28887. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  28888. offset += 16;
  28889. instancesCount++;
  28890. }
  28891. }
  28892. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  28893. if (instancesBuffer) {
  28894. instancesBuffer.dispose();
  28895. }
  28896. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  28897. this._instancesBuffer = instancesBuffer;
  28898. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  28899. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  28900. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  28901. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  28902. }
  28903. else {
  28904. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  28905. }
  28906. this._bind(subMesh, effect, fillMode);
  28907. this._draw(subMesh, fillMode, instancesCount);
  28908. engine.unbindInstanceAttributes();
  28909. return this;
  28910. };
  28911. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  28912. var scene = this.getScene();
  28913. var engine = scene.getEngine();
  28914. if (hardwareInstancedRendering) {
  28915. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  28916. }
  28917. else {
  28918. if (batch.renderSelf[subMesh._id]) {
  28919. // Draw
  28920. if (onBeforeDraw) {
  28921. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  28922. }
  28923. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  28924. }
  28925. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  28926. if (visibleInstancesForSubMesh) {
  28927. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  28928. var instance = visibleInstancesForSubMesh[instanceIndex];
  28929. // World
  28930. var world = instance.getWorldMatrix();
  28931. if (onBeforeDraw) {
  28932. onBeforeDraw(true, world, effectiveMaterial);
  28933. }
  28934. // Draw
  28935. this._draw(subMesh, fillMode);
  28936. }
  28937. }
  28938. }
  28939. return this;
  28940. };
  28941. /**
  28942. * Triggers the draw call for the mesh.
  28943. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  28944. * Returns the Mesh.
  28945. */
  28946. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  28947. this.checkOcclusionQuery();
  28948. if (this._isOccluded) {
  28949. return this;
  28950. }
  28951. var scene = this.getScene();
  28952. // Managing instances
  28953. var batch = this._getInstancesRenderList(subMesh._id);
  28954. if (batch.mustReturn) {
  28955. return this;
  28956. }
  28957. // Checking geometry state
  28958. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  28959. return this;
  28960. }
  28961. this.onBeforeRenderObservable.notifyObservers(this);
  28962. var engine = scene.getEngine();
  28963. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  28964. // Material
  28965. var material = subMesh.getMaterial();
  28966. if (!material) {
  28967. return this;
  28968. }
  28969. this._effectiveMaterial = material;
  28970. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28971. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  28972. return this;
  28973. }
  28974. }
  28975. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  28976. return this;
  28977. }
  28978. // Alpha mode
  28979. if (enableAlphaMode) {
  28980. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  28981. }
  28982. // Outline - step 1
  28983. var savedDepthWrite = engine.getDepthWrite();
  28984. if (this.renderOutline) {
  28985. engine.setDepthWrite(false);
  28986. scene.getOutlineRenderer().render(subMesh, batch);
  28987. engine.setDepthWrite(savedDepthWrite);
  28988. }
  28989. var effect;
  28990. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  28991. effect = subMesh.effect;
  28992. }
  28993. else {
  28994. effect = this._effectiveMaterial.getEffect();
  28995. }
  28996. if (!effect) {
  28997. return this;
  28998. }
  28999. var sideOrientation = this.overrideMaterialSideOrientation;
  29000. if (sideOrientation == null) {
  29001. sideOrientation = this._effectiveMaterial.sideOrientation;
  29002. if (this._getWorldMatrixDeterminant() < 0) {
  29003. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  29004. }
  29005. }
  29006. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  29007. if (this._effectiveMaterial.forceDepthWrite) {
  29008. engine.setDepthWrite(true);
  29009. }
  29010. // Bind
  29011. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  29012. if (!hardwareInstancedRendering) {
  29013. this._bind(subMesh, effect, fillMode);
  29014. }
  29015. var world = this.getWorldMatrix();
  29016. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  29017. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  29018. }
  29019. else {
  29020. this._effectiveMaterial.bind(world, this);
  29021. }
  29022. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  29023. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  29024. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  29025. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  29026. }
  29027. // Draw
  29028. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  29029. // Unbind
  29030. this._effectiveMaterial.unbind();
  29031. // Outline - step 2
  29032. if (this.renderOutline && savedDepthWrite) {
  29033. engine.setDepthWrite(true);
  29034. engine.setColorWrite(false);
  29035. scene.getOutlineRenderer().render(subMesh, batch);
  29036. engine.setColorWrite(true);
  29037. }
  29038. // Overlay
  29039. if (this.renderOverlay) {
  29040. var currentMode = engine.getAlphaMode();
  29041. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  29042. scene.getOutlineRenderer().render(subMesh, batch, true);
  29043. engine.setAlphaMode(currentMode);
  29044. }
  29045. this.onAfterRenderObservable.notifyObservers(this);
  29046. return this;
  29047. };
  29048. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  29049. if (isInstance && effectiveMaterial) {
  29050. effectiveMaterial.bindOnlyWorldMatrix(world);
  29051. }
  29052. };
  29053. /**
  29054. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  29055. */
  29056. Mesh.prototype.getEmittedParticleSystems = function () {
  29057. var results = new Array();
  29058. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  29059. var particleSystem = this.getScene().particleSystems[index];
  29060. if (particleSystem.emitter === this) {
  29061. results.push(particleSystem);
  29062. }
  29063. }
  29064. return results;
  29065. };
  29066. /**
  29067. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  29068. */
  29069. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  29070. var results = new Array();
  29071. var descendants = this.getDescendants();
  29072. descendants.push(this);
  29073. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  29074. var particleSystem = this.getScene().particleSystems[index];
  29075. var emitter = particleSystem.emitter;
  29076. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  29077. results.push(particleSystem);
  29078. }
  29079. }
  29080. return results;
  29081. };
  29082. Mesh.prototype._checkDelayState = function () {
  29083. var scene = this.getScene();
  29084. if (this._geometry) {
  29085. this._geometry.load(scene);
  29086. }
  29087. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  29088. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  29089. this._queueLoad(scene);
  29090. }
  29091. return this;
  29092. };
  29093. Mesh.prototype._queueLoad = function (scene) {
  29094. var _this = this;
  29095. scene._addPendingData(this);
  29096. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  29097. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  29098. if (data instanceof ArrayBuffer) {
  29099. _this._delayLoadingFunction(data, _this);
  29100. }
  29101. else {
  29102. _this._delayLoadingFunction(JSON.parse(data), _this);
  29103. }
  29104. _this.instances.forEach(function (instance) {
  29105. instance._syncSubMeshes();
  29106. });
  29107. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  29108. scene._removePendingData(_this);
  29109. }, function () { }, scene.database, getBinaryData);
  29110. return this;
  29111. };
  29112. /**
  29113. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  29114. */
  29115. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  29116. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  29117. return false;
  29118. }
  29119. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  29120. return false;
  29121. }
  29122. this._checkDelayState();
  29123. return true;
  29124. };
  29125. /**
  29126. * Sets the mesh material by the material or multiMaterial `id` property.
  29127. * The material `id` is a string identifying the material or the multiMaterial.
  29128. * This method returns the Mesh.
  29129. */
  29130. Mesh.prototype.setMaterialByID = function (id) {
  29131. var materials = this.getScene().materials;
  29132. var index;
  29133. for (index = materials.length - 1; index > -1; index--) {
  29134. if (materials[index].id === id) {
  29135. this.material = materials[index];
  29136. return this;
  29137. }
  29138. }
  29139. // Multi
  29140. var multiMaterials = this.getScene().multiMaterials;
  29141. for (index = multiMaterials.length - 1; index > -1; index--) {
  29142. if (multiMaterials[index].id === id) {
  29143. this.material = multiMaterials[index];
  29144. return this;
  29145. }
  29146. }
  29147. return this;
  29148. };
  29149. /**
  29150. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  29151. */
  29152. Mesh.prototype.getAnimatables = function () {
  29153. var results = new Array();
  29154. if (this.material) {
  29155. results.push(this.material);
  29156. }
  29157. if (this.skeleton) {
  29158. results.push(this.skeleton);
  29159. }
  29160. return results;
  29161. };
  29162. /**
  29163. * Modifies the mesh geometry according to the passed transformation matrix.
  29164. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  29165. * The mesh normals are modified accordingly the same transformation.
  29166. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  29167. * Note that, under the hood, this method sets a new VertexBuffer each call.
  29168. * Returns the Mesh.
  29169. */
  29170. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  29171. // Position
  29172. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  29173. return this;
  29174. }
  29175. var submeshes = this.subMeshes.splice(0);
  29176. this._resetPointsArrayCache();
  29177. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29178. var temp = new Array();
  29179. var index;
  29180. for (index = 0; index < data.length; index += 3) {
  29181. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  29182. }
  29183. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  29184. // Normals
  29185. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  29186. return this;
  29187. }
  29188. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29189. temp = [];
  29190. for (index = 0; index < data.length; index += 3) {
  29191. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  29192. }
  29193. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  29194. // flip faces?
  29195. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  29196. this.flipFaces();
  29197. }
  29198. // Restore submeshes
  29199. this.releaseSubMeshes();
  29200. this.subMeshes = submeshes;
  29201. return this;
  29202. };
  29203. /**
  29204. * Modifies the mesh geometry according to its own current World Matrix.
  29205. * The mesh World Matrix is then reset.
  29206. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  29207. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  29208. * Note that, under the hood, this method sets a new VertexBuffer each call.
  29209. * Returns the Mesh.
  29210. */
  29211. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  29212. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  29213. this.scaling.copyFromFloats(1, 1, 1);
  29214. this.position.copyFromFloats(0, 0, 0);
  29215. this.rotation.copyFromFloats(0, 0, 0);
  29216. //only if quaternion is already set
  29217. if (this.rotationQuaternion) {
  29218. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  29219. }
  29220. this._worldMatrix = BABYLON.Matrix.Identity();
  29221. return this;
  29222. };
  29223. Object.defineProperty(Mesh.prototype, "_positions", {
  29224. // Cache
  29225. get: function () {
  29226. if (this._geometry) {
  29227. return this._geometry._positions;
  29228. }
  29229. return null;
  29230. },
  29231. enumerable: true,
  29232. configurable: true
  29233. });
  29234. Mesh.prototype._resetPointsArrayCache = function () {
  29235. if (this._geometry) {
  29236. this._geometry._resetPointsArrayCache();
  29237. }
  29238. return this;
  29239. };
  29240. Mesh.prototype._generatePointsArray = function () {
  29241. if (this._geometry) {
  29242. return this._geometry._generatePointsArray();
  29243. }
  29244. return false;
  29245. };
  29246. /**
  29247. * Returns a new Mesh object generated from the current mesh properties.
  29248. * This method must not get confused with createInstance().
  29249. * The parameter `name` is a string, the name given to the new mesh.
  29250. * The optional parameter `newParent` can be any Node object (default `null`).
  29251. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  29252. * 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.
  29253. */
  29254. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  29255. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  29256. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  29257. };
  29258. /**
  29259. * Releases resources associated with this mesh.
  29260. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  29261. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  29262. */
  29263. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  29264. var _this = this;
  29265. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  29266. this.morphTargetManager = null;
  29267. if (this._geometry) {
  29268. this._geometry.releaseForMesh(this, true);
  29269. }
  29270. // Sources
  29271. var meshes = this.getScene().meshes;
  29272. meshes.forEach(function (abstractMesh) {
  29273. var mesh = abstractMesh;
  29274. if (mesh._source && mesh._source === _this) {
  29275. mesh._source = null;
  29276. }
  29277. });
  29278. this._source = null;
  29279. // Instances
  29280. if (this._instancesBuffer) {
  29281. this._instancesBuffer.dispose();
  29282. this._instancesBuffer = null;
  29283. }
  29284. while (this.instances.length) {
  29285. this.instances[0].dispose();
  29286. }
  29287. // Effect layers.
  29288. var effectLayers = this.getScene().effectLayers;
  29289. for (var i = 0; i < effectLayers.length; i++) {
  29290. var effectLayer = effectLayers[i];
  29291. if (effectLayer) {
  29292. effectLayer._disposeMesh(this);
  29293. }
  29294. }
  29295. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  29296. };
  29297. /**
  29298. * Modifies the mesh geometry according to a displacement map.
  29299. * 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.
  29300. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  29301. * This method returns nothing.
  29302. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  29303. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  29304. * 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.
  29305. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  29306. * The parameter `uvScale` is an optional vector2 used to scale UV.
  29307. *
  29308. * Returns the Mesh.
  29309. */
  29310. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  29311. var _this = this;
  29312. var scene = this.getScene();
  29313. var onload = function (img) {
  29314. // Getting height map data
  29315. var canvas = document.createElement("canvas");
  29316. var context = canvas.getContext("2d");
  29317. var heightMapWidth = img.width;
  29318. var heightMapHeight = img.height;
  29319. canvas.width = heightMapWidth;
  29320. canvas.height = heightMapHeight;
  29321. context.drawImage(img, 0, 0);
  29322. // Create VertexData from map data
  29323. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  29324. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  29325. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  29326. //execute success callback, if set
  29327. if (onSuccess) {
  29328. onSuccess(_this);
  29329. }
  29330. };
  29331. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  29332. return this;
  29333. };
  29334. /**
  29335. * Modifies the mesh geometry according to a displacementMap buffer.
  29336. * 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.
  29337. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  29338. * This method returns nothing.
  29339. * 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.
  29340. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  29341. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  29342. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  29343. * The parameter `uvScale` is an optional vector2 used to scale UV.
  29344. *
  29345. * Returns the Mesh.
  29346. */
  29347. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  29348. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  29349. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  29350. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  29351. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  29352. return this;
  29353. }
  29354. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29355. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  29356. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  29357. var position = BABYLON.Vector3.Zero();
  29358. var normal = BABYLON.Vector3.Zero();
  29359. var uv = BABYLON.Vector2.Zero();
  29360. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  29361. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  29362. for (var index = 0; index < positions.length; index += 3) {
  29363. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  29364. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  29365. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  29366. // Compute height
  29367. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  29368. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  29369. var pos = (u + v * heightMapWidth) * 4;
  29370. var r = buffer[pos] / 255.0;
  29371. var g = buffer[pos + 1] / 255.0;
  29372. var b = buffer[pos + 2] / 255.0;
  29373. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  29374. normal.normalize();
  29375. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  29376. position = position.add(normal);
  29377. position.toArray(positions, index);
  29378. }
  29379. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  29380. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  29381. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  29382. return this;
  29383. };
  29384. /**
  29385. * Modify the mesh to get a flat shading rendering.
  29386. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  29387. * This method returns the Mesh.
  29388. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  29389. */
  29390. Mesh.prototype.convertToFlatShadedMesh = function () {
  29391. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  29392. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  29393. var kinds = this.getVerticesDataKinds();
  29394. var vbs = {};
  29395. var data = {};
  29396. var newdata = {};
  29397. var updatableNormals = false;
  29398. var kindIndex;
  29399. var kind;
  29400. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29401. kind = kinds[kindIndex];
  29402. var vertexBuffer = this.getVertexBuffer(kind);
  29403. if (kind === BABYLON.VertexBuffer.NormalKind) {
  29404. updatableNormals = vertexBuffer.isUpdatable();
  29405. kinds.splice(kindIndex, 1);
  29406. kindIndex--;
  29407. continue;
  29408. }
  29409. vbs[kind] = vertexBuffer;
  29410. data[kind] = vbs[kind].getData();
  29411. newdata[kind] = [];
  29412. }
  29413. // Save previous submeshes
  29414. var previousSubmeshes = this.subMeshes.slice(0);
  29415. var indices = this.getIndices();
  29416. var totalIndices = this.getTotalIndices();
  29417. // Generating unique vertices per face
  29418. var index;
  29419. for (index = 0; index < totalIndices; index++) {
  29420. var vertexIndex = indices[index];
  29421. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29422. kind = kinds[kindIndex];
  29423. var stride = vbs[kind].getStrideSize();
  29424. for (var offset = 0; offset < stride; offset++) {
  29425. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  29426. }
  29427. }
  29428. }
  29429. // Updating faces & normal
  29430. var normals = [];
  29431. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  29432. for (index = 0; index < totalIndices; index += 3) {
  29433. indices[index] = index;
  29434. indices[index + 1] = index + 1;
  29435. indices[index + 2] = index + 2;
  29436. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  29437. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  29438. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  29439. var p1p2 = p1.subtract(p2);
  29440. var p3p2 = p3.subtract(p2);
  29441. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  29442. // Store same normals for every vertex
  29443. for (var localIndex = 0; localIndex < 3; localIndex++) {
  29444. normals.push(normal.x);
  29445. normals.push(normal.y);
  29446. normals.push(normal.z);
  29447. }
  29448. }
  29449. this.setIndices(indices);
  29450. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  29451. // Updating vertex buffers
  29452. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29453. kind = kinds[kindIndex];
  29454. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29455. }
  29456. // Updating submeshes
  29457. this.releaseSubMeshes();
  29458. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29459. var previousOne = previousSubmeshes[submeshIndex];
  29460. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29461. }
  29462. this.synchronizeInstances();
  29463. return this;
  29464. };
  29465. /**
  29466. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  29467. * In other words, more vertices, no more indices and a single bigger VBO.
  29468. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  29469. * Returns the Mesh.
  29470. */
  29471. Mesh.prototype.convertToUnIndexedMesh = function () {
  29472. /// <summary>Remove indices by unfolding faces into buffers</summary>
  29473. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  29474. var kinds = this.getVerticesDataKinds();
  29475. var vbs = {};
  29476. var data = {};
  29477. var newdata = {};
  29478. var kindIndex;
  29479. var kind;
  29480. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29481. kind = kinds[kindIndex];
  29482. var vertexBuffer = this.getVertexBuffer(kind);
  29483. vbs[kind] = vertexBuffer;
  29484. data[kind] = vbs[kind].getData();
  29485. newdata[kind] = [];
  29486. }
  29487. // Save previous submeshes
  29488. var previousSubmeshes = this.subMeshes.slice(0);
  29489. var indices = this.getIndices();
  29490. var totalIndices = this.getTotalIndices();
  29491. // Generating unique vertices per face
  29492. var index;
  29493. for (index = 0; index < totalIndices; index++) {
  29494. var vertexIndex = indices[index];
  29495. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29496. kind = kinds[kindIndex];
  29497. var stride = vbs[kind].getStrideSize();
  29498. for (var offset = 0; offset < stride; offset++) {
  29499. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  29500. }
  29501. }
  29502. }
  29503. // Updating indices
  29504. for (index = 0; index < totalIndices; index += 3) {
  29505. indices[index] = index;
  29506. indices[index + 1] = index + 1;
  29507. indices[index + 2] = index + 2;
  29508. }
  29509. this.setIndices(indices);
  29510. // Updating vertex buffers
  29511. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  29512. kind = kinds[kindIndex];
  29513. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  29514. }
  29515. // Updating submeshes
  29516. this.releaseSubMeshes();
  29517. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  29518. var previousOne = previousSubmeshes[submeshIndex];
  29519. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  29520. }
  29521. this._unIndexed = true;
  29522. this.synchronizeInstances();
  29523. return this;
  29524. };
  29525. /**
  29526. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  29527. * This method returns the Mesh.
  29528. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  29529. */
  29530. Mesh.prototype.flipFaces = function (flipNormals) {
  29531. if (flipNormals === void 0) { flipNormals = false; }
  29532. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  29533. var i;
  29534. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  29535. for (i = 0; i < vertex_data.normals.length; i++) {
  29536. vertex_data.normals[i] *= -1;
  29537. }
  29538. }
  29539. if (vertex_data.indices) {
  29540. var temp;
  29541. for (i = 0; i < vertex_data.indices.length; i += 3) {
  29542. // reassign indices
  29543. temp = vertex_data.indices[i + 1];
  29544. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  29545. vertex_data.indices[i + 2] = temp;
  29546. }
  29547. }
  29548. vertex_data.applyToMesh(this);
  29549. return this;
  29550. };
  29551. // Instances
  29552. /**
  29553. * Creates a new InstancedMesh object from the mesh model.
  29554. * An instance shares the same properties and the same material than its model.
  29555. * Only these properties of each instance can then be set individually :
  29556. * - position
  29557. * - rotation
  29558. * - rotationQuaternion
  29559. * - setPivotMatrix
  29560. * - scaling
  29561. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  29562. * Warning : this method is not supported for Line mesh and LineSystem
  29563. */
  29564. Mesh.prototype.createInstance = function (name) {
  29565. return new BABYLON.InstancedMesh(name, this);
  29566. };
  29567. /**
  29568. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  29569. * After this call, all the mesh instances have the same submeshes than the current mesh.
  29570. * This method returns the Mesh.
  29571. */
  29572. Mesh.prototype.synchronizeInstances = function () {
  29573. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  29574. var instance = this.instances[instanceIndex];
  29575. instance._syncSubMeshes();
  29576. }
  29577. return this;
  29578. };
  29579. /**
  29580. * Simplify the mesh according to the given array of settings.
  29581. * Function will return immediately and will simplify async. It returns the Mesh.
  29582. * @param settings a collection of simplification settings.
  29583. * @param parallelProcessing should all levels calculate parallel or one after the other.
  29584. * @param type the type of simplification to run.
  29585. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  29586. */
  29587. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  29588. if (parallelProcessing === void 0) { parallelProcessing = true; }
  29589. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  29590. this.getScene().simplificationQueue.addTask({
  29591. settings: settings,
  29592. parallelProcessing: parallelProcessing,
  29593. mesh: this,
  29594. simplificationType: simplificationType,
  29595. successCallback: successCallback
  29596. });
  29597. return this;
  29598. };
  29599. /**
  29600. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  29601. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  29602. * This should be used together with the simplification to avoid disappearing triangles.
  29603. * Returns the Mesh.
  29604. * @param successCallback an optional success callback to be called after the optimization finished.
  29605. */
  29606. Mesh.prototype.optimizeIndices = function (successCallback) {
  29607. var _this = this;
  29608. var indices = this.getIndices();
  29609. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  29610. if (!positions || !indices) {
  29611. return this;
  29612. }
  29613. var vectorPositions = new Array();
  29614. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  29615. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  29616. }
  29617. var dupes = new Array();
  29618. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  29619. var realPos = vectorPositions.length - 1 - iteration;
  29620. var testedPosition = vectorPositions[realPos];
  29621. for (var j = 0; j < realPos; ++j) {
  29622. var againstPosition = vectorPositions[j];
  29623. if (testedPosition.equals(againstPosition)) {
  29624. dupes[realPos] = j;
  29625. break;
  29626. }
  29627. }
  29628. }, function () {
  29629. for (var i = 0; i < indices.length; ++i) {
  29630. indices[i] = dupes[indices[i]] || indices[i];
  29631. }
  29632. //indices are now reordered
  29633. var originalSubMeshes = _this.subMeshes.slice(0);
  29634. _this.setIndices(indices);
  29635. _this.subMeshes = originalSubMeshes;
  29636. if (successCallback) {
  29637. successCallback(_this);
  29638. }
  29639. });
  29640. return this;
  29641. };
  29642. Mesh.prototype.serialize = function (serializationObject) {
  29643. serializationObject.name = this.name;
  29644. serializationObject.id = this.id;
  29645. serializationObject.type = this.getClassName();
  29646. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  29647. serializationObject.tags = BABYLON.Tags.GetTags(this);
  29648. }
  29649. serializationObject.position = this.position.asArray();
  29650. if (this.rotationQuaternion) {
  29651. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  29652. }
  29653. else if (this.rotation) {
  29654. serializationObject.rotation = this.rotation.asArray();
  29655. }
  29656. serializationObject.scaling = this.scaling.asArray();
  29657. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  29658. serializationObject.isEnabled = this.isEnabled(false);
  29659. serializationObject.isVisible = this.isVisible;
  29660. serializationObject.infiniteDistance = this.infiniteDistance;
  29661. serializationObject.pickable = this.isPickable;
  29662. serializationObject.receiveShadows = this.receiveShadows;
  29663. serializationObject.billboardMode = this.billboardMode;
  29664. serializationObject.visibility = this.visibility;
  29665. serializationObject.checkCollisions = this.checkCollisions;
  29666. serializationObject.isBlocker = this.isBlocker;
  29667. // Parent
  29668. if (this.parent) {
  29669. serializationObject.parentId = this.parent.id;
  29670. }
  29671. // Geometry
  29672. serializationObject.isUnIndexed = this.isUnIndexed;
  29673. var geometry = this._geometry;
  29674. if (geometry) {
  29675. var geometryId = geometry.id;
  29676. serializationObject.geometryId = geometryId;
  29677. // SubMeshes
  29678. serializationObject.subMeshes = [];
  29679. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  29680. var subMesh = this.subMeshes[subIndex];
  29681. serializationObject.subMeshes.push({
  29682. materialIndex: subMesh.materialIndex,
  29683. verticesStart: subMesh.verticesStart,
  29684. verticesCount: subMesh.verticesCount,
  29685. indexStart: subMesh.indexStart,
  29686. indexCount: subMesh.indexCount
  29687. });
  29688. }
  29689. }
  29690. // Material
  29691. if (this.material) {
  29692. serializationObject.materialId = this.material.id;
  29693. }
  29694. else {
  29695. this.material = null;
  29696. }
  29697. // Morph targets
  29698. if (this.morphTargetManager) {
  29699. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  29700. }
  29701. // Skeleton
  29702. if (this.skeleton) {
  29703. serializationObject.skeletonId = this.skeleton.id;
  29704. }
  29705. // Physics
  29706. //TODO implement correct serialization for physics impostors.
  29707. var impostor = this.getPhysicsImpostor();
  29708. if (impostor) {
  29709. serializationObject.physicsMass = impostor.getParam("mass");
  29710. serializationObject.physicsFriction = impostor.getParam("friction");
  29711. serializationObject.physicsRestitution = impostor.getParam("mass");
  29712. serializationObject.physicsImpostor = impostor.type;
  29713. }
  29714. // Metadata
  29715. if (this.metadata) {
  29716. serializationObject.metadata = this.metadata;
  29717. }
  29718. // Instances
  29719. serializationObject.instances = [];
  29720. for (var index = 0; index < this.instances.length; index++) {
  29721. var instance = this.instances[index];
  29722. var serializationInstance = {
  29723. name: instance.name,
  29724. id: instance.id,
  29725. position: instance.position.asArray(),
  29726. scaling: instance.scaling.asArray()
  29727. };
  29728. if (instance.rotationQuaternion) {
  29729. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  29730. }
  29731. else if (instance.rotation) {
  29732. serializationInstance.rotation = instance.rotation.asArray();
  29733. }
  29734. serializationObject.instances.push(serializationInstance);
  29735. // Animations
  29736. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  29737. serializationInstance.ranges = instance.serializeAnimationRanges();
  29738. }
  29739. //
  29740. // Animations
  29741. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29742. serializationObject.ranges = this.serializeAnimationRanges();
  29743. // Layer mask
  29744. serializationObject.layerMask = this.layerMask;
  29745. // Alpha
  29746. serializationObject.alphaIndex = this.alphaIndex;
  29747. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  29748. // Overlay
  29749. serializationObject.overlayAlpha = this.overlayAlpha;
  29750. serializationObject.overlayColor = this.overlayColor.asArray();
  29751. serializationObject.renderOverlay = this.renderOverlay;
  29752. // Fog
  29753. serializationObject.applyFog = this.applyFog;
  29754. // Action Manager
  29755. if (this.actionManager) {
  29756. serializationObject.actions = this.actionManager.serialize(this.name);
  29757. }
  29758. };
  29759. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  29760. if (!this.geometry) {
  29761. return;
  29762. }
  29763. this._markSubMeshesAsAttributesDirty();
  29764. var morphTargetManager = this._morphTargetManager;
  29765. if (morphTargetManager && morphTargetManager.vertexCount) {
  29766. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  29767. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  29768. this.morphTargetManager = null;
  29769. return;
  29770. }
  29771. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  29772. var morphTarget = morphTargetManager.getActiveTarget(index);
  29773. var positions = morphTarget.getPositions();
  29774. if (!positions) {
  29775. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  29776. return;
  29777. }
  29778. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  29779. var normals = morphTarget.getNormals();
  29780. if (normals) {
  29781. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  29782. }
  29783. var tangents = morphTarget.getTangents();
  29784. if (tangents) {
  29785. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  29786. }
  29787. }
  29788. }
  29789. else {
  29790. var index = 0;
  29791. // Positions
  29792. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  29793. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  29794. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  29795. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  29796. }
  29797. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  29798. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  29799. }
  29800. index++;
  29801. }
  29802. }
  29803. };
  29804. // Statics
  29805. /**
  29806. * Returns a new Mesh object parsed from the source provided.
  29807. * The parameter `parsedMesh` is the source.
  29808. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  29809. */
  29810. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  29811. var mesh;
  29812. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  29813. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  29814. }
  29815. else {
  29816. mesh = new Mesh(parsedMesh.name, scene);
  29817. }
  29818. mesh.id = parsedMesh.id;
  29819. if (BABYLON.Tags) {
  29820. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  29821. }
  29822. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  29823. if (parsedMesh.metadata !== undefined) {
  29824. mesh.metadata = parsedMesh.metadata;
  29825. }
  29826. if (parsedMesh.rotationQuaternion) {
  29827. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  29828. }
  29829. else if (parsedMesh.rotation) {
  29830. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  29831. }
  29832. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  29833. if (parsedMesh.localMatrix) {
  29834. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  29835. }
  29836. else if (parsedMesh.pivotMatrix) {
  29837. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  29838. }
  29839. mesh.setEnabled(parsedMesh.isEnabled);
  29840. mesh.isVisible = parsedMesh.isVisible;
  29841. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  29842. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  29843. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  29844. if (parsedMesh.applyFog !== undefined) {
  29845. mesh.applyFog = parsedMesh.applyFog;
  29846. }
  29847. if (parsedMesh.pickable !== undefined) {
  29848. mesh.isPickable = parsedMesh.pickable;
  29849. }
  29850. if (parsedMesh.alphaIndex !== undefined) {
  29851. mesh.alphaIndex = parsedMesh.alphaIndex;
  29852. }
  29853. mesh.receiveShadows = parsedMesh.receiveShadows;
  29854. mesh.billboardMode = parsedMesh.billboardMode;
  29855. if (parsedMesh.visibility !== undefined) {
  29856. mesh.visibility = parsedMesh.visibility;
  29857. }
  29858. mesh.checkCollisions = parsedMesh.checkCollisions;
  29859. if (parsedMesh.isBlocker !== undefined) {
  29860. mesh.isBlocker = parsedMesh.isBlocker;
  29861. }
  29862. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  29863. // freezeWorldMatrix
  29864. if (parsedMesh.freezeWorldMatrix) {
  29865. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  29866. }
  29867. // Parent
  29868. if (parsedMesh.parentId) {
  29869. mesh._waitingParentId = parsedMesh.parentId;
  29870. }
  29871. // Actions
  29872. if (parsedMesh.actions !== undefined) {
  29873. mesh._waitingActions = parsedMesh.actions;
  29874. }
  29875. // Overlay
  29876. if (parsedMesh.overlayAlpha !== undefined) {
  29877. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  29878. }
  29879. if (parsedMesh.overlayColor !== undefined) {
  29880. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  29881. }
  29882. if (parsedMesh.renderOverlay !== undefined) {
  29883. mesh.renderOverlay = parsedMesh.renderOverlay;
  29884. }
  29885. // Geometry
  29886. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  29887. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  29888. if (parsedMesh.delayLoadingFile) {
  29889. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29890. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  29891. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  29892. if (parsedMesh._binaryInfo) {
  29893. mesh._binaryInfo = parsedMesh._binaryInfo;
  29894. }
  29895. mesh._delayInfo = [];
  29896. if (parsedMesh.hasUVs) {
  29897. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  29898. }
  29899. if (parsedMesh.hasUVs2) {
  29900. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  29901. }
  29902. if (parsedMesh.hasUVs3) {
  29903. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  29904. }
  29905. if (parsedMesh.hasUVs4) {
  29906. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  29907. }
  29908. if (parsedMesh.hasUVs5) {
  29909. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  29910. }
  29911. if (parsedMesh.hasUVs6) {
  29912. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  29913. }
  29914. if (parsedMesh.hasColors) {
  29915. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  29916. }
  29917. if (parsedMesh.hasMatricesIndices) {
  29918. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29919. }
  29920. if (parsedMesh.hasMatricesWeights) {
  29921. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29922. }
  29923. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  29924. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  29925. mesh._checkDelayState();
  29926. }
  29927. }
  29928. else {
  29929. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  29930. }
  29931. // Material
  29932. if (parsedMesh.materialId) {
  29933. mesh.setMaterialByID(parsedMesh.materialId);
  29934. }
  29935. else {
  29936. mesh.material = null;
  29937. }
  29938. // Morph targets
  29939. if (parsedMesh.morphTargetManagerId > -1) {
  29940. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  29941. }
  29942. // Skeleton
  29943. if (parsedMesh.skeletonId > -1) {
  29944. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  29945. if (parsedMesh.numBoneInfluencers) {
  29946. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  29947. }
  29948. }
  29949. // Animations
  29950. if (parsedMesh.animations) {
  29951. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  29952. var parsedAnimation = parsedMesh.animations[animationIndex];
  29953. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29954. }
  29955. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  29956. }
  29957. if (parsedMesh.autoAnimate) {
  29958. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  29959. }
  29960. // Layer Mask
  29961. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  29962. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  29963. }
  29964. else {
  29965. mesh.layerMask = 0x0FFFFFFF;
  29966. }
  29967. // Physics
  29968. if (parsedMesh.physicsImpostor) {
  29969. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  29970. mass: parsedMesh.physicsMass,
  29971. friction: parsedMesh.physicsFriction,
  29972. restitution: parsedMesh.physicsRestitution
  29973. }, scene);
  29974. }
  29975. // Instances
  29976. if (parsedMesh.instances) {
  29977. for (var index = 0; index < parsedMesh.instances.length; index++) {
  29978. var parsedInstance = parsedMesh.instances[index];
  29979. var instance = mesh.createInstance(parsedInstance.name);
  29980. if (parsedInstance.id) {
  29981. instance.id = parsedInstance.id;
  29982. }
  29983. if (BABYLON.Tags) {
  29984. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  29985. }
  29986. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  29987. if (parsedInstance.parentId) {
  29988. instance._waitingParentId = parsedInstance.parentId;
  29989. }
  29990. if (parsedInstance.rotationQuaternion) {
  29991. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  29992. }
  29993. else if (parsedInstance.rotation) {
  29994. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  29995. }
  29996. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  29997. instance.checkCollisions = mesh.checkCollisions;
  29998. if (parsedMesh.animations) {
  29999. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  30000. parsedAnimation = parsedMesh.animations[animationIndex];
  30001. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30002. }
  30003. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  30004. }
  30005. }
  30006. }
  30007. return mesh;
  30008. };
  30009. /**
  30010. * Creates a ribbon mesh.
  30011. * Please consider using the same method from the MeshBuilder class instead.
  30012. * 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.
  30013. *
  30014. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  30015. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  30016. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  30017. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  30018. * 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.
  30019. * 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.
  30020. * 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
  30021. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30022. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30023. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30024. */
  30025. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  30026. if (closeArray === void 0) { closeArray = false; }
  30027. if (updatable === void 0) { updatable = false; }
  30028. return BABYLON.MeshBuilder.CreateRibbon(name, {
  30029. pathArray: pathArray,
  30030. closeArray: closeArray,
  30031. closePath: closePath,
  30032. offset: offset,
  30033. updatable: updatable,
  30034. sideOrientation: sideOrientation,
  30035. instance: instance
  30036. }, scene);
  30037. };
  30038. /**
  30039. * Creates a plane polygonal mesh. By default, this is a disc.
  30040. * Please consider using the same method from the MeshBuilder class instead.
  30041. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  30042. * 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.
  30043. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30044. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30045. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30046. */
  30047. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  30048. if (scene === void 0) { scene = null; }
  30049. var options = {
  30050. radius: radius,
  30051. tessellation: tessellation,
  30052. sideOrientation: sideOrientation,
  30053. updatable: updatable
  30054. };
  30055. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  30056. };
  30057. /**
  30058. * Creates a box mesh.
  30059. * Please consider using the same method from the MeshBuilder class instead.
  30060. * The parameter `size` sets the size (float) of each box side (default 1).
  30061. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30062. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30063. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30064. */
  30065. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  30066. if (scene === void 0) { scene = null; }
  30067. var options = {
  30068. size: size,
  30069. sideOrientation: sideOrientation,
  30070. updatable: updatable
  30071. };
  30072. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  30073. };
  30074. /**
  30075. * Creates a sphere mesh.
  30076. * Please consider using the same method from the MeshBuilder class instead.
  30077. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  30078. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  30079. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30080. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30081. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30082. */
  30083. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  30084. var options = {
  30085. segments: segments,
  30086. diameterX: diameter,
  30087. diameterY: diameter,
  30088. diameterZ: diameter,
  30089. sideOrientation: sideOrientation,
  30090. updatable: updatable
  30091. };
  30092. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  30093. };
  30094. /**
  30095. * Creates a cylinder or a cone mesh.
  30096. * Please consider using the same method from the MeshBuilder class instead.
  30097. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  30098. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  30099. * 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.
  30100. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  30101. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  30102. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30103. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30104. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30105. */
  30106. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  30107. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  30108. if (scene !== undefined) {
  30109. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  30110. updatable = scene;
  30111. }
  30112. scene = subdivisions;
  30113. subdivisions = 1;
  30114. }
  30115. var options = {
  30116. height: height,
  30117. diameterTop: diameterTop,
  30118. diameterBottom: diameterBottom,
  30119. tessellation: tessellation,
  30120. subdivisions: subdivisions,
  30121. sideOrientation: sideOrientation,
  30122. updatable: updatable
  30123. };
  30124. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  30125. };
  30126. // Torus (Code from SharpDX.org)
  30127. /**
  30128. * Creates a torus mesh.
  30129. * Please consider using the same method from the MeshBuilder class instead.
  30130. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  30131. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  30132. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  30133. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30134. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30135. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30136. */
  30137. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  30138. var options = {
  30139. diameter: diameter,
  30140. thickness: thickness,
  30141. tessellation: tessellation,
  30142. sideOrientation: sideOrientation,
  30143. updatable: updatable
  30144. };
  30145. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  30146. };
  30147. /**
  30148. * Creates a torus knot mesh.
  30149. * Please consider using the same method from the MeshBuilder class instead.
  30150. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  30151. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  30152. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  30153. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  30154. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30155. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30156. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30157. */
  30158. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  30159. var options = {
  30160. radius: radius,
  30161. tube: tube,
  30162. radialSegments: radialSegments,
  30163. tubularSegments: tubularSegments,
  30164. p: p,
  30165. q: q,
  30166. sideOrientation: sideOrientation,
  30167. updatable: updatable
  30168. };
  30169. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  30170. };
  30171. /**
  30172. * Creates a line mesh.
  30173. * Please consider using the same method from the MeshBuilder class instead.
  30174. * 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.
  30175. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  30176. * The parameter `points` is an array successive Vector3.
  30177. * 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
  30178. * When updating an instance, remember that only point positions can change, not the number of points.
  30179. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30180. */
  30181. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  30182. if (scene === void 0) { scene = null; }
  30183. if (updatable === void 0) { updatable = false; }
  30184. if (instance === void 0) { instance = null; }
  30185. var options = {
  30186. points: points,
  30187. updatable: updatable,
  30188. instance: instance
  30189. };
  30190. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  30191. };
  30192. /**
  30193. * Creates a dashed line mesh.
  30194. * Please consider using the same method from the MeshBuilder class instead.
  30195. * 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.
  30196. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  30197. * The parameter `points` is an array successive Vector3.
  30198. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  30199. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  30200. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  30201. * 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
  30202. * When updating an instance, remember that only point positions can change, not the number of points.
  30203. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30204. */
  30205. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  30206. if (scene === void 0) { scene = null; }
  30207. var options = {
  30208. points: points,
  30209. dashSize: dashSize,
  30210. gapSize: gapSize,
  30211. dashNb: dashNb,
  30212. updatable: updatable,
  30213. instance: instance
  30214. };
  30215. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  30216. };
  30217. /**
  30218. * Creates a polygon mesh.
  30219. * Please consider using the same method from the MeshBuilder class instead.
  30220. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  30221. * 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.
  30222. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30223. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30224. * Remember you can only change the shape positions, not their number when updating a polygon.
  30225. */
  30226. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  30227. var options = {
  30228. shape: shape,
  30229. holes: holes,
  30230. updatable: updatable,
  30231. sideOrientation: sideOrientation
  30232. };
  30233. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  30234. };
  30235. /**
  30236. * Creates an extruded polygon mesh, with depth in the Y direction.
  30237. * Please consider using the same method from the MeshBuilder class instead.
  30238. */
  30239. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  30240. var options = {
  30241. shape: shape,
  30242. holes: holes,
  30243. depth: depth,
  30244. updatable: updatable,
  30245. sideOrientation: sideOrientation
  30246. };
  30247. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  30248. };
  30249. /**
  30250. * Creates an extruded shape mesh.
  30251. * 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.
  30252. * Please consider using the same method from the MeshBuilder class instead.
  30253. *
  30254. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  30255. * 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
  30256. * extruded along the Z axis.
  30257. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  30258. * 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.
  30259. * The parameter `scale` (float, default 1) is the value to scale the shape.
  30260. * 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
  30261. * 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
  30262. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  30263. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30264. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30265. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30266. */
  30267. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  30268. if (scene === void 0) { scene = null; }
  30269. var options = {
  30270. shape: shape,
  30271. path: path,
  30272. scale: scale,
  30273. rotation: rotation,
  30274. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  30275. sideOrientation: sideOrientation,
  30276. instance: instance,
  30277. updatable: updatable
  30278. };
  30279. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  30280. };
  30281. /**
  30282. * Creates an custom extruded shape mesh.
  30283. * 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.
  30284. * Please consider using the same method from the MeshBuilder class instead.
  30285. *
  30286. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  30287. * 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
  30288. * extruded along the Z axis.
  30289. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  30290. * 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
  30291. * and the distance of this point from the begining of the path :
  30292. * ```javascript
  30293. * var rotationFunction = function(i, distance) {
  30294. * // do things
  30295. * return rotationValue; }
  30296. * ```
  30297. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  30298. * 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
  30299. * and the distance of this point from the begining of the path :
  30300. * ```javascript
  30301. * var scaleFunction = function(i, distance) {
  30302. * // do things
  30303. * return scaleValue;}
  30304. * ```
  30305. * It must returns a float value that will be the scale value applied to the shape on each path point.
  30306. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  30307. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  30308. * 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
  30309. * 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
  30310. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  30311. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30312. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30313. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30314. */
  30315. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  30316. var options = {
  30317. shape: shape,
  30318. path: path,
  30319. scaleFunction: scaleFunction,
  30320. rotationFunction: rotationFunction,
  30321. ribbonCloseArray: ribbonCloseArray,
  30322. ribbonClosePath: ribbonClosePath,
  30323. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  30324. sideOrientation: sideOrientation,
  30325. instance: instance,
  30326. updatable: updatable
  30327. };
  30328. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  30329. };
  30330. /**
  30331. * Creates lathe mesh.
  30332. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  30333. * Please consider using the same method from the MeshBuilder class instead.
  30334. * 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
  30335. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  30336. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  30337. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  30338. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30339. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30340. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30341. */
  30342. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  30343. var options = {
  30344. shape: shape,
  30345. radius: radius,
  30346. tessellation: tessellation,
  30347. sideOrientation: sideOrientation,
  30348. updatable: updatable
  30349. };
  30350. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  30351. };
  30352. /**
  30353. * Creates a plane mesh.
  30354. * Please consider using the same method from the MeshBuilder class instead.
  30355. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  30356. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30357. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30358. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30359. */
  30360. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  30361. var options = {
  30362. size: size,
  30363. width: size,
  30364. height: size,
  30365. sideOrientation: sideOrientation,
  30366. updatable: updatable
  30367. };
  30368. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  30369. };
  30370. /**
  30371. * Creates a ground mesh.
  30372. * Please consider using the same method from the MeshBuilder class instead.
  30373. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  30374. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  30375. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30376. */
  30377. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  30378. var options = {
  30379. width: width,
  30380. height: height,
  30381. subdivisions: subdivisions,
  30382. updatable: updatable
  30383. };
  30384. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  30385. };
  30386. /**
  30387. * Creates a tiled ground mesh.
  30388. * Please consider using the same method from the MeshBuilder class instead.
  30389. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  30390. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  30391. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  30392. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  30393. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  30394. * numbers of subdivisions on the ground width and height of each tile.
  30395. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30396. */
  30397. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  30398. var options = {
  30399. xmin: xmin,
  30400. zmin: zmin,
  30401. xmax: xmax,
  30402. zmax: zmax,
  30403. subdivisions: subdivisions,
  30404. precision: precision,
  30405. updatable: updatable
  30406. };
  30407. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  30408. };
  30409. /**
  30410. * Creates a ground mesh from a height map.
  30411. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  30412. * Please consider using the same method from the MeshBuilder class instead.
  30413. * The parameter `url` sets the URL of the height map image resource.
  30414. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  30415. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  30416. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  30417. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  30418. * 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).
  30419. * This function is passed the newly built mesh :
  30420. * ```javascript
  30421. * function(mesh) { // do things
  30422. * return; }
  30423. * ```
  30424. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30425. */
  30426. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  30427. var options = {
  30428. width: width,
  30429. height: height,
  30430. subdivisions: subdivisions,
  30431. minHeight: minHeight,
  30432. maxHeight: maxHeight,
  30433. updatable: updatable,
  30434. onReady: onReady
  30435. };
  30436. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  30437. };
  30438. /**
  30439. * Creates a tube mesh.
  30440. * 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.
  30441. * Please consider using the same method from the MeshBuilder class instead.
  30442. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  30443. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  30444. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  30445. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  30446. * 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.
  30447. * It must return a radius value (positive float) :
  30448. * ```javascript
  30449. * var radiusFunction = function(i, distance) {
  30450. * // do things
  30451. * return radius; }
  30452. * ```
  30453. * 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
  30454. * 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
  30455. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30456. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30457. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30458. */
  30459. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  30460. var options = {
  30461. path: path,
  30462. radius: radius,
  30463. tessellation: tessellation,
  30464. radiusFunction: radiusFunction,
  30465. arc: 1,
  30466. cap: cap,
  30467. updatable: updatable,
  30468. sideOrientation: sideOrientation,
  30469. instance: instance
  30470. };
  30471. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  30472. };
  30473. /**
  30474. * Creates a polyhedron mesh.
  30475. * Please consider using the same method from the MeshBuilder class instead.
  30476. * 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
  30477. * to choose the wanted type.
  30478. * The parameter `size` (positive float, default 1) sets the polygon size.
  30479. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  30480. * 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`.
  30481. * 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
  30482. * 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)`).
  30483. * 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
  30484. * 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.
  30485. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30486. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30487. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30488. */
  30489. Mesh.CreatePolyhedron = function (name, options, scene) {
  30490. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  30491. };
  30492. /**
  30493. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  30494. * Please consider using the same method from the MeshBuilder class instead.
  30495. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  30496. * 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`).
  30497. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  30498. * 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.
  30499. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  30500. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  30501. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  30502. */
  30503. Mesh.CreateIcoSphere = function (name, options, scene) {
  30504. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  30505. };
  30506. /**
  30507. * Creates a decal mesh.
  30508. * Please consider using the same method from the MeshBuilder class instead.
  30509. * 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.
  30510. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  30511. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  30512. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  30513. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  30514. */
  30515. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  30516. var options = {
  30517. position: position,
  30518. normal: normal,
  30519. size: size,
  30520. angle: angle
  30521. };
  30522. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  30523. };
  30524. // Skeletons
  30525. /**
  30526. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30527. */
  30528. Mesh.prototype.setPositionsForCPUSkinning = function () {
  30529. if (!this._sourcePositions) {
  30530. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30531. if (!source) {
  30532. return this._sourcePositions;
  30533. }
  30534. this._sourcePositions = new Float32Array(source);
  30535. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  30536. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  30537. }
  30538. }
  30539. return this._sourcePositions;
  30540. };
  30541. /**
  30542. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  30543. */
  30544. Mesh.prototype.setNormalsForCPUSkinning = function () {
  30545. if (!this._sourceNormals) {
  30546. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30547. if (!source) {
  30548. return this._sourceNormals;
  30549. }
  30550. this._sourceNormals = new Float32Array(source);
  30551. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  30552. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  30553. }
  30554. }
  30555. return this._sourceNormals;
  30556. };
  30557. /**
  30558. * Updates the vertex buffer by applying transformation from the bones.
  30559. * Returns the Mesh.
  30560. *
  30561. * @param {skeleton} skeleton to apply
  30562. */
  30563. Mesh.prototype.applySkeleton = function (skeleton) {
  30564. if (!this.geometry) {
  30565. return this;
  30566. }
  30567. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  30568. return this;
  30569. }
  30570. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  30571. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  30572. return this;
  30573. }
  30574. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  30575. return this;
  30576. }
  30577. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  30578. return this;
  30579. }
  30580. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  30581. return this;
  30582. }
  30583. if (!this._sourcePositions) {
  30584. var submeshes = this.subMeshes.slice();
  30585. this.setPositionsForCPUSkinning();
  30586. this.subMeshes = submeshes;
  30587. }
  30588. if (!this._sourceNormals) {
  30589. this.setNormalsForCPUSkinning();
  30590. }
  30591. // positionsData checks for not being Float32Array will only pass at most once
  30592. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30593. if (!positionsData) {
  30594. return this;
  30595. }
  30596. if (!(positionsData instanceof Float32Array)) {
  30597. positionsData = new Float32Array(positionsData);
  30598. }
  30599. // normalsData checks for not being Float32Array will only pass at most once
  30600. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  30601. if (!normalsData) {
  30602. return this;
  30603. }
  30604. if (!(normalsData instanceof Float32Array)) {
  30605. normalsData = new Float32Array(normalsData);
  30606. }
  30607. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  30608. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  30609. if (!matricesWeightsData || !matricesIndicesData) {
  30610. return this;
  30611. }
  30612. var needExtras = this.numBoneInfluencers > 4;
  30613. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  30614. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  30615. var skeletonMatrices = skeleton.getTransformMatrices(this);
  30616. var tempVector3 = BABYLON.Vector3.Zero();
  30617. var finalMatrix = new BABYLON.Matrix();
  30618. var tempMatrix = new BABYLON.Matrix();
  30619. var matWeightIdx = 0;
  30620. var inf;
  30621. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  30622. var weight;
  30623. for (inf = 0; inf < 4; inf++) {
  30624. weight = matricesWeightsData[matWeightIdx + inf];
  30625. if (weight > 0) {
  30626. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30627. finalMatrix.addToSelf(tempMatrix);
  30628. }
  30629. else
  30630. break;
  30631. }
  30632. if (needExtras) {
  30633. for (inf = 0; inf < 4; inf++) {
  30634. weight = matricesWeightsExtraData[matWeightIdx + inf];
  30635. if (weight > 0) {
  30636. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  30637. finalMatrix.addToSelf(tempMatrix);
  30638. }
  30639. else
  30640. break;
  30641. }
  30642. }
  30643. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  30644. tempVector3.toArray(positionsData, index);
  30645. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  30646. tempVector3.toArray(normalsData, index);
  30647. finalMatrix.reset();
  30648. }
  30649. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  30650. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  30651. return this;
  30652. };
  30653. // Tools
  30654. /**
  30655. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  30656. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  30657. */
  30658. Mesh.MinMax = function (meshes) {
  30659. var minVector = null;
  30660. var maxVector = null;
  30661. meshes.forEach(function (mesh, index, array) {
  30662. var boundingInfo = mesh.getBoundingInfo();
  30663. var boundingBox = boundingInfo.boundingBox;
  30664. if (!minVector || !maxVector) {
  30665. minVector = boundingBox.minimumWorld;
  30666. maxVector = boundingBox.maximumWorld;
  30667. }
  30668. else {
  30669. minVector.minimizeInPlace(boundingBox.minimumWorld);
  30670. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  30671. }
  30672. });
  30673. if (!minVector || !maxVector) {
  30674. return {
  30675. min: BABYLON.Vector3.Zero(),
  30676. max: BABYLON.Vector3.Zero()
  30677. };
  30678. }
  30679. return {
  30680. min: minVector,
  30681. max: maxVector
  30682. };
  30683. };
  30684. /**
  30685. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  30686. */
  30687. Mesh.Center = function (meshesOrMinMaxVector) {
  30688. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  30689. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  30690. };
  30691. /**
  30692. * Merge the array of meshes into a single mesh for performance reasons.
  30693. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  30694. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  30695. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  30696. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  30697. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  30698. */
  30699. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  30700. if (disposeSource === void 0) { disposeSource = true; }
  30701. var index;
  30702. if (!allow32BitsIndices) {
  30703. var totalVertices = 0;
  30704. // Counting vertices
  30705. for (index = 0; index < meshes.length; index++) {
  30706. if (meshes[index]) {
  30707. totalVertices += meshes[index].getTotalVertices();
  30708. if (totalVertices > 65536) {
  30709. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  30710. return null;
  30711. }
  30712. }
  30713. }
  30714. }
  30715. // Merge
  30716. var vertexData = null;
  30717. var otherVertexData;
  30718. var indiceArray = new Array();
  30719. var source = null;
  30720. for (index = 0; index < meshes.length; index++) {
  30721. if (meshes[index]) {
  30722. meshes[index].computeWorldMatrix(true);
  30723. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  30724. otherVertexData.transform(meshes[index].getWorldMatrix());
  30725. if (vertexData) {
  30726. vertexData.merge(otherVertexData);
  30727. }
  30728. else {
  30729. vertexData = otherVertexData;
  30730. source = meshes[index];
  30731. }
  30732. if (subdivideWithSubMeshes) {
  30733. indiceArray.push(meshes[index].getTotalIndices());
  30734. }
  30735. }
  30736. }
  30737. source = source;
  30738. if (!meshSubclass) {
  30739. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  30740. }
  30741. vertexData.applyToMesh(meshSubclass);
  30742. // Setting properties
  30743. meshSubclass.material = source.material;
  30744. meshSubclass.checkCollisions = source.checkCollisions;
  30745. // Cleaning
  30746. if (disposeSource) {
  30747. for (index = 0; index < meshes.length; index++) {
  30748. if (meshes[index]) {
  30749. meshes[index].dispose();
  30750. }
  30751. }
  30752. }
  30753. // Subdivide
  30754. if (subdivideWithSubMeshes) {
  30755. //-- Suppresions du submesh global
  30756. meshSubclass.releaseSubMeshes();
  30757. index = 0;
  30758. var offset = 0;
  30759. //-- aplique la subdivision en fonction du tableau d'indices
  30760. while (index < indiceArray.length) {
  30761. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  30762. offset += indiceArray[index];
  30763. index++;
  30764. }
  30765. }
  30766. return meshSubclass;
  30767. };
  30768. // Consts
  30769. Mesh._FRONTSIDE = 0;
  30770. Mesh._BACKSIDE = 1;
  30771. Mesh._DOUBLESIDE = 2;
  30772. Mesh._DEFAULTSIDE = 0;
  30773. Mesh._NO_CAP = 0;
  30774. Mesh._CAP_START = 1;
  30775. Mesh._CAP_END = 2;
  30776. Mesh._CAP_ALL = 3;
  30777. return Mesh;
  30778. }(BABYLON.AbstractMesh));
  30779. BABYLON.Mesh = Mesh;
  30780. })(BABYLON || (BABYLON = {}));
  30781. //# sourceMappingURL=babylon.mesh.js.map
  30782. "use strict";
  30783. var BABYLON;
  30784. (function (BABYLON) {
  30785. var BaseSubMesh = /** @class */ (function () {
  30786. function BaseSubMesh() {
  30787. }
  30788. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  30789. get: function () {
  30790. return this._materialEffect;
  30791. },
  30792. enumerable: true,
  30793. configurable: true
  30794. });
  30795. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  30796. if (defines === void 0) { defines = null; }
  30797. if (this._materialEffect === effect) {
  30798. if (!effect) {
  30799. this._materialDefines = null;
  30800. }
  30801. return;
  30802. }
  30803. this._materialDefines = defines;
  30804. this._materialEffect = effect;
  30805. };
  30806. return BaseSubMesh;
  30807. }());
  30808. BABYLON.BaseSubMesh = BaseSubMesh;
  30809. var SubMesh = /** @class */ (function (_super) {
  30810. __extends(SubMesh, _super);
  30811. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30812. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30813. var _this = _super.call(this) || this;
  30814. _this.materialIndex = materialIndex;
  30815. _this.verticesStart = verticesStart;
  30816. _this.verticesCount = verticesCount;
  30817. _this.indexStart = indexStart;
  30818. _this.indexCount = indexCount;
  30819. _this._renderId = 0;
  30820. _this._mesh = mesh;
  30821. _this._renderingMesh = renderingMesh || mesh;
  30822. mesh.subMeshes.push(_this);
  30823. _this._trianglePlanes = [];
  30824. _this._id = mesh.subMeshes.length - 1;
  30825. if (createBoundingBox) {
  30826. _this.refreshBoundingInfo();
  30827. mesh.computeWorldMatrix(true);
  30828. }
  30829. return _this;
  30830. }
  30831. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  30832. if (createBoundingBox === void 0) { createBoundingBox = true; }
  30833. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  30834. };
  30835. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  30836. get: function () {
  30837. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  30838. },
  30839. enumerable: true,
  30840. configurable: true
  30841. });
  30842. /**
  30843. * Returns the submesh BoudingInfo object.
  30844. */
  30845. SubMesh.prototype.getBoundingInfo = function () {
  30846. if (this.IsGlobal) {
  30847. return this._mesh.getBoundingInfo();
  30848. }
  30849. return this._boundingInfo;
  30850. };
  30851. /**
  30852. * Sets the submesh BoundingInfo.
  30853. * Return the SubMesh.
  30854. */
  30855. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  30856. this._boundingInfo = boundingInfo;
  30857. return this;
  30858. };
  30859. /**
  30860. * Returns the mesh of the current submesh.
  30861. */
  30862. SubMesh.prototype.getMesh = function () {
  30863. return this._mesh;
  30864. };
  30865. /**
  30866. * Returns the rendering mesh of the submesh.
  30867. */
  30868. SubMesh.prototype.getRenderingMesh = function () {
  30869. return this._renderingMesh;
  30870. };
  30871. /**
  30872. * Returns the submesh material.
  30873. */
  30874. SubMesh.prototype.getMaterial = function () {
  30875. var rootMaterial = this._renderingMesh.material;
  30876. if (rootMaterial === null || rootMaterial === undefined) {
  30877. return this._mesh.getScene().defaultMaterial;
  30878. }
  30879. else if (rootMaterial.getSubMaterial) {
  30880. var multiMaterial = rootMaterial;
  30881. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  30882. if (this._currentMaterial !== effectiveMaterial) {
  30883. this._currentMaterial = effectiveMaterial;
  30884. this._materialDefines = null;
  30885. }
  30886. return effectiveMaterial;
  30887. }
  30888. return rootMaterial;
  30889. };
  30890. // Methods
  30891. /**
  30892. * Sets a new updated BoundingInfo object to the submesh.
  30893. * Returns the SubMesh.
  30894. */
  30895. SubMesh.prototype.refreshBoundingInfo = function () {
  30896. this._lastColliderWorldVertices = null;
  30897. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  30898. return this;
  30899. }
  30900. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  30901. if (!data) {
  30902. this._boundingInfo = this._mesh.getBoundingInfo();
  30903. return this;
  30904. }
  30905. var indices = this._renderingMesh.getIndices();
  30906. var extend;
  30907. //is this the only submesh?
  30908. if (this.indexStart === 0 && this.indexCount === indices.length) {
  30909. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30910. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  30911. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  30912. }
  30913. else {
  30914. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  30915. }
  30916. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  30917. return this;
  30918. };
  30919. SubMesh.prototype._checkCollision = function (collider) {
  30920. var boundingInfo = this._renderingMesh.getBoundingInfo();
  30921. return boundingInfo._checkCollision(collider);
  30922. };
  30923. /**
  30924. * Updates the submesh BoundingInfo.
  30925. * Returns the Submesh.
  30926. */
  30927. SubMesh.prototype.updateBoundingInfo = function (world) {
  30928. var boundingInfo = this.getBoundingInfo();
  30929. if (!boundingInfo) {
  30930. this.refreshBoundingInfo();
  30931. boundingInfo = this.getBoundingInfo();
  30932. }
  30933. boundingInfo.update(world);
  30934. return this;
  30935. };
  30936. /**
  30937. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  30938. * Boolean returned.
  30939. */
  30940. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  30941. var boundingInfo = this.getBoundingInfo();
  30942. if (!boundingInfo) {
  30943. return false;
  30944. }
  30945. return boundingInfo.isInFrustum(frustumPlanes);
  30946. };
  30947. /**
  30948. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  30949. * Boolean returned.
  30950. */
  30951. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  30952. var boundingInfo = this.getBoundingInfo();
  30953. if (!boundingInfo) {
  30954. return false;
  30955. }
  30956. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  30957. };
  30958. /**
  30959. * Renders the submesh.
  30960. * Returns it.
  30961. */
  30962. SubMesh.prototype.render = function (enableAlphaMode) {
  30963. this._renderingMesh.render(this, enableAlphaMode);
  30964. return this;
  30965. };
  30966. /**
  30967. * Returns a new Index Buffer.
  30968. * Type returned : WebGLBuffer.
  30969. */
  30970. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  30971. if (!this._linesIndexBuffer) {
  30972. var linesIndices = [];
  30973. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  30974. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  30975. }
  30976. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  30977. this.linesIndexCount = linesIndices.length;
  30978. }
  30979. return this._linesIndexBuffer;
  30980. };
  30981. /**
  30982. * True is the passed Ray intersects the submesh bounding box.
  30983. * Boolean returned.
  30984. */
  30985. SubMesh.prototype.canIntersects = function (ray) {
  30986. var boundingInfo = this.getBoundingInfo();
  30987. if (!boundingInfo) {
  30988. return false;
  30989. }
  30990. return ray.intersectsBox(boundingInfo.boundingBox);
  30991. };
  30992. /**
  30993. * Returns an object IntersectionInfo.
  30994. */
  30995. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  30996. var intersectInfo = null;
  30997. var material = this.getMaterial();
  30998. if (!material) {
  30999. return null;
  31000. }
  31001. switch (material.fillMode) {
  31002. case BABYLON.Material.PointListDrawMode:
  31003. case BABYLON.Material.LineListDrawMode:
  31004. case BABYLON.Material.LineLoopDrawMode:
  31005. case BABYLON.Material.LineStripDrawMode:
  31006. case BABYLON.Material.TriangleFanDrawMode:
  31007. case BABYLON.Material.TriangleStripDrawMode:
  31008. return null;
  31009. }
  31010. // LineMesh first as it's also a Mesh...
  31011. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  31012. var lineMesh = this._mesh;
  31013. // Line test
  31014. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  31015. var p0 = positions[indices[index]];
  31016. var p1 = positions[indices[index + 1]];
  31017. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  31018. if (length < 0) {
  31019. continue;
  31020. }
  31021. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  31022. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  31023. if (fastCheck) {
  31024. break;
  31025. }
  31026. }
  31027. }
  31028. }
  31029. else {
  31030. // Triangles test
  31031. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  31032. var p0 = positions[indices[index]];
  31033. var p1 = positions[indices[index + 1]];
  31034. var p2 = positions[indices[index + 2]];
  31035. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  31036. if (currentIntersectInfo) {
  31037. if (currentIntersectInfo.distance < 0) {
  31038. continue;
  31039. }
  31040. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  31041. intersectInfo = currentIntersectInfo;
  31042. intersectInfo.faceId = index / 3;
  31043. if (fastCheck) {
  31044. break;
  31045. }
  31046. }
  31047. }
  31048. }
  31049. }
  31050. return intersectInfo;
  31051. };
  31052. SubMesh.prototype._rebuild = function () {
  31053. if (this._linesIndexBuffer) {
  31054. this._linesIndexBuffer = null;
  31055. }
  31056. };
  31057. // Clone
  31058. /**
  31059. * Creates a new Submesh from the passed Mesh.
  31060. */
  31061. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  31062. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  31063. if (!this.IsGlobal) {
  31064. var boundingInfo = this.getBoundingInfo();
  31065. if (!boundingInfo) {
  31066. return result;
  31067. }
  31068. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  31069. }
  31070. return result;
  31071. };
  31072. // Dispose
  31073. /**
  31074. * Disposes the Submesh.
  31075. * Returns nothing.
  31076. */
  31077. SubMesh.prototype.dispose = function () {
  31078. if (this._linesIndexBuffer) {
  31079. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  31080. this._linesIndexBuffer = null;
  31081. }
  31082. // Remove from mesh
  31083. var index = this._mesh.subMeshes.indexOf(this);
  31084. this._mesh.subMeshes.splice(index, 1);
  31085. };
  31086. // Statics
  31087. /**
  31088. * Creates a new Submesh from the passed parameters :
  31089. * - materialIndex (integer) : the index of the main mesh material.
  31090. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  31091. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  31092. * - mesh (Mesh) : the main mesh to create the submesh from.
  31093. * - renderingMesh (optional Mesh) : rendering mesh.
  31094. */
  31095. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  31096. var minVertexIndex = Number.MAX_VALUE;
  31097. var maxVertexIndex = -Number.MAX_VALUE;
  31098. renderingMesh = (renderingMesh || mesh);
  31099. var indices = renderingMesh.getIndices();
  31100. for (var index = startIndex; index < startIndex + indexCount; index++) {
  31101. var vertexIndex = indices[index];
  31102. if (vertexIndex < minVertexIndex)
  31103. minVertexIndex = vertexIndex;
  31104. if (vertexIndex > maxVertexIndex)
  31105. maxVertexIndex = vertexIndex;
  31106. }
  31107. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  31108. };
  31109. return SubMesh;
  31110. }(BaseSubMesh));
  31111. BABYLON.SubMesh = SubMesh;
  31112. })(BABYLON || (BABYLON = {}));
  31113. //# sourceMappingURL=babylon.subMesh.js.map
  31114. "use strict";
  31115. var __assign = (this && this.__assign) || Object.assign || function(t) {
  31116. for (var s, i = 1, n = arguments.length; i < n; i++) {
  31117. s = arguments[i];
  31118. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  31119. t[p] = s[p];
  31120. }
  31121. return t;
  31122. };
  31123. var BABYLON;
  31124. (function (BABYLON) {
  31125. /**
  31126. * Manages the defines for the Material.
  31127. */
  31128. var MaterialDefines = /** @class */ (function () {
  31129. function MaterialDefines() {
  31130. this._isDirty = true;
  31131. this._areLightsDirty = true;
  31132. this._areAttributesDirty = true;
  31133. this._areTexturesDirty = true;
  31134. this._areFresnelDirty = true;
  31135. this._areMiscDirty = true;
  31136. this._areImageProcessingDirty = true;
  31137. this._normals = false;
  31138. this._uvs = false;
  31139. this._needNormals = false;
  31140. this._needUVs = false;
  31141. }
  31142. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  31143. /**
  31144. * Specifies if the material needs to be re-calculated.
  31145. */
  31146. get: function () {
  31147. return this._isDirty;
  31148. },
  31149. enumerable: true,
  31150. configurable: true
  31151. });
  31152. /**
  31153. * Marks the material to indicate that it has been re-calculated.
  31154. */
  31155. MaterialDefines.prototype.markAsProcessed = function () {
  31156. this._isDirty = false;
  31157. this._areAttributesDirty = false;
  31158. this._areTexturesDirty = false;
  31159. this._areFresnelDirty = false;
  31160. this._areLightsDirty = false;
  31161. this._areMiscDirty = false;
  31162. this._areImageProcessingDirty = false;
  31163. };
  31164. /**
  31165. * Marks the material to indicate that it needs to be re-calculated.
  31166. */
  31167. MaterialDefines.prototype.markAsUnprocessed = function () {
  31168. this._isDirty = true;
  31169. };
  31170. /**
  31171. * Marks the material to indicate all of its defines need to be re-calculated.
  31172. */
  31173. MaterialDefines.prototype.markAllAsDirty = function () {
  31174. this._areTexturesDirty = true;
  31175. this._areAttributesDirty = true;
  31176. this._areLightsDirty = true;
  31177. this._areFresnelDirty = true;
  31178. this._areMiscDirty = true;
  31179. this._areImageProcessingDirty = true;
  31180. this._isDirty = true;
  31181. };
  31182. /**
  31183. * Marks the material to indicate that image processing needs to be re-calculated.
  31184. */
  31185. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  31186. this._areImageProcessingDirty = true;
  31187. this._isDirty = true;
  31188. };
  31189. /**
  31190. * Marks the material to indicate the lights need to be re-calculated.
  31191. */
  31192. MaterialDefines.prototype.markAsLightDirty = function () {
  31193. this._areLightsDirty = true;
  31194. this._isDirty = true;
  31195. };
  31196. /**
  31197. * Marks the attribute state as changed.
  31198. */
  31199. MaterialDefines.prototype.markAsAttributesDirty = function () {
  31200. this._areAttributesDirty = true;
  31201. this._isDirty = true;
  31202. };
  31203. /**
  31204. * Marks the texture state as changed.
  31205. */
  31206. MaterialDefines.prototype.markAsTexturesDirty = function () {
  31207. this._areTexturesDirty = true;
  31208. this._isDirty = true;
  31209. };
  31210. /**
  31211. * Marks the fresnel state as changed.
  31212. */
  31213. MaterialDefines.prototype.markAsFresnelDirty = function () {
  31214. this._areFresnelDirty = true;
  31215. this._isDirty = true;
  31216. };
  31217. /**
  31218. * Marks the misc state as changed.
  31219. */
  31220. MaterialDefines.prototype.markAsMiscDirty = function () {
  31221. this._areMiscDirty = true;
  31222. this._isDirty = true;
  31223. };
  31224. /**
  31225. * Rebuilds the material defines.
  31226. */
  31227. MaterialDefines.prototype.rebuild = function () {
  31228. if (this._keys) {
  31229. delete this._keys;
  31230. }
  31231. this._keys = [];
  31232. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  31233. var key = _a[_i];
  31234. if (key[0] === "_") {
  31235. continue;
  31236. }
  31237. this._keys.push(key);
  31238. }
  31239. };
  31240. /**
  31241. * Specifies if two material defines are equal.
  31242. * @param other - A material define instance to compare to.
  31243. * @returns - Boolean indicating if the material defines are equal (true) or not (false).
  31244. */
  31245. MaterialDefines.prototype.isEqual = function (other) {
  31246. if (this._keys.length !== other._keys.length) {
  31247. return false;
  31248. }
  31249. for (var index = 0; index < this._keys.length; index++) {
  31250. var prop = this._keys[index];
  31251. if (this[prop] !== other[prop]) {
  31252. return false;
  31253. }
  31254. }
  31255. return true;
  31256. };
  31257. /**
  31258. * Clones this instance's defines to another instance.
  31259. * @param other - material defines to clone values to.
  31260. */
  31261. MaterialDefines.prototype.cloneTo = function (other) {
  31262. if (this._keys.length !== other._keys.length) {
  31263. other._keys = this._keys.slice(0);
  31264. }
  31265. for (var index = 0; index < this._keys.length; index++) {
  31266. var prop = this._keys[index];
  31267. other[prop] = this[prop];
  31268. }
  31269. };
  31270. /**
  31271. * Resets the material define values.
  31272. */
  31273. MaterialDefines.prototype.reset = function () {
  31274. for (var index = 0; index < this._keys.length; index++) {
  31275. var prop = this._keys[index];
  31276. var type = typeof this[prop];
  31277. switch (type) {
  31278. case "number":
  31279. this[prop] = 0;
  31280. break;
  31281. case "string":
  31282. this[prop] = "";
  31283. break;
  31284. default:
  31285. this[prop] = false;
  31286. break;
  31287. }
  31288. }
  31289. };
  31290. /**
  31291. * Converts the material define values to a string.
  31292. * @returns - String of material define information.
  31293. */
  31294. MaterialDefines.prototype.toString = function () {
  31295. var result = "";
  31296. for (var index = 0; index < this._keys.length; index++) {
  31297. var prop = this._keys[index];
  31298. var value = this[prop];
  31299. var type = typeof value;
  31300. switch (type) {
  31301. case "number":
  31302. case "string":
  31303. result += "#define " + prop + " " + value + "\n";
  31304. break;
  31305. default:
  31306. if (value) {
  31307. result += "#define " + prop + "\n";
  31308. }
  31309. break;
  31310. }
  31311. }
  31312. return result;
  31313. };
  31314. return MaterialDefines;
  31315. }());
  31316. BABYLON.MaterialDefines = MaterialDefines;
  31317. /**
  31318. * This offers the main features of a material in BJS.
  31319. */
  31320. var Material = /** @class */ (function () {
  31321. /**
  31322. * Creates a material instance.
  31323. * @param name - The name of the material.
  31324. * @param scene - The BJS scene to reference.
  31325. * @param doNotAdd - Specifies if the material should be added to the scene.
  31326. */
  31327. function Material(name, scene, doNotAdd) {
  31328. /**
  31329. * Specifies if the ready state should be checked on each call.
  31330. */
  31331. this.checkReadyOnEveryCall = false;
  31332. /**
  31333. * Specifies if the ready state should be checked once.
  31334. */
  31335. this.checkReadyOnlyOnce = false;
  31336. /**
  31337. * The state of the material.
  31338. */
  31339. this.state = "";
  31340. /**
  31341. * The alpha value of the material.
  31342. */
  31343. this._alpha = 1.0;
  31344. /**
  31345. * Specifies if back face culling is enabled.
  31346. */
  31347. this._backFaceCulling = true;
  31348. /**
  31349. * Specifies if the material should be serialized.
  31350. */
  31351. this.doNotSerialize = false;
  31352. /**
  31353. * Specifies if the effect should be stored on sub meshes.
  31354. */
  31355. this.storeEffectOnSubMeshes = false;
  31356. /**
  31357. * An event triggered when the material is disposed.
  31358. * @type {BABYLON.Observable}
  31359. */
  31360. this.onDisposeObservable = new BABYLON.Observable();
  31361. /**
  31362. * An event triggered when the material is bound.
  31363. * @type {BABYLON.Observable}
  31364. */
  31365. this.onBindObservable = new BABYLON.Observable();
  31366. /**
  31367. * An event triggered when the material is unbound.
  31368. * @type {BABYLON.Observable}
  31369. */
  31370. this.onUnBindObservable = new BABYLON.Observable();
  31371. /**
  31372. * Stores the value of the alpha mode.
  31373. */
  31374. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  31375. /**
  31376. * Stores the state of the need depth pre-pass value.
  31377. */
  31378. this._needDepthPrePass = false;
  31379. /**
  31380. * Specifies if depth writing should be disabled.
  31381. */
  31382. this.disableDepthWrite = false;
  31383. /**
  31384. * Specifies if depth writing should be forced.
  31385. */
  31386. this.forceDepthWrite = false;
  31387. /**
  31388. * Specifies if there should be a separate pass for culling.
  31389. */
  31390. this.separateCullingPass = false;
  31391. /**
  31392. * Stores the state specifing if fog should be enabled.
  31393. */
  31394. this._fogEnabled = true;
  31395. /**
  31396. * Stores the size of points.
  31397. */
  31398. this.pointSize = 1.0;
  31399. /**
  31400. * Stores the z offset value.
  31401. */
  31402. this.zOffset = 0;
  31403. /**
  31404. * Specifies if the material was previously ready.
  31405. */
  31406. this._wasPreviouslyReady = false;
  31407. /**
  31408. * Stores the fill mode state.
  31409. */
  31410. this._fillMode = Material.TriangleFillMode;
  31411. this.name = name;
  31412. this.id = name || BABYLON.Tools.RandomId();
  31413. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  31414. if (this._scene.useRightHandedSystem) {
  31415. this.sideOrientation = Material.ClockWiseSideOrientation;
  31416. }
  31417. else {
  31418. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  31419. }
  31420. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  31421. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  31422. if (!doNotAdd) {
  31423. this._scene.materials.push(this);
  31424. }
  31425. }
  31426. Object.defineProperty(Material, "TriangleFillMode", {
  31427. /**
  31428. * Returns the triangle fill mode.
  31429. */
  31430. get: function () {
  31431. return Material._TriangleFillMode;
  31432. },
  31433. enumerable: true,
  31434. configurable: true
  31435. });
  31436. Object.defineProperty(Material, "WireFrameFillMode", {
  31437. /**
  31438. * Returns the wireframe mode.
  31439. */
  31440. get: function () {
  31441. return Material._WireFrameFillMode;
  31442. },
  31443. enumerable: true,
  31444. configurable: true
  31445. });
  31446. Object.defineProperty(Material, "PointFillMode", {
  31447. /**
  31448. * Returns the point fill mode.
  31449. */
  31450. get: function () {
  31451. return Material._PointFillMode;
  31452. },
  31453. enumerable: true,
  31454. configurable: true
  31455. });
  31456. Object.defineProperty(Material, "PointListDrawMode", {
  31457. /**
  31458. * Returns the point list draw mode.
  31459. */
  31460. get: function () {
  31461. return Material._PointListDrawMode;
  31462. },
  31463. enumerable: true,
  31464. configurable: true
  31465. });
  31466. Object.defineProperty(Material, "LineListDrawMode", {
  31467. /**
  31468. * Returns the line list draw mode.
  31469. */
  31470. get: function () {
  31471. return Material._LineListDrawMode;
  31472. },
  31473. enumerable: true,
  31474. configurable: true
  31475. });
  31476. Object.defineProperty(Material, "LineLoopDrawMode", {
  31477. /**
  31478. * Returns the line loop draw mode.
  31479. */
  31480. get: function () {
  31481. return Material._LineLoopDrawMode;
  31482. },
  31483. enumerable: true,
  31484. configurable: true
  31485. });
  31486. Object.defineProperty(Material, "LineStripDrawMode", {
  31487. /**
  31488. * Returns the line strip draw mode.
  31489. */
  31490. get: function () {
  31491. return Material._LineStripDrawMode;
  31492. },
  31493. enumerable: true,
  31494. configurable: true
  31495. });
  31496. Object.defineProperty(Material, "TriangleStripDrawMode", {
  31497. /**
  31498. * Returns the triangle strip draw mode.
  31499. */
  31500. get: function () {
  31501. return Material._TriangleStripDrawMode;
  31502. },
  31503. enumerable: true,
  31504. configurable: true
  31505. });
  31506. Object.defineProperty(Material, "TriangleFanDrawMode", {
  31507. /**
  31508. * Returns the triangle fan draw mode.
  31509. */
  31510. get: function () {
  31511. return Material._TriangleFanDrawMode;
  31512. },
  31513. enumerable: true,
  31514. configurable: true
  31515. });
  31516. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  31517. /**
  31518. * Returns the clock-wise side orientation.
  31519. */
  31520. get: function () {
  31521. return Material._ClockWiseSideOrientation;
  31522. },
  31523. enumerable: true,
  31524. configurable: true
  31525. });
  31526. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  31527. /**
  31528. * Returns the counter clock-wise side orientation.
  31529. */
  31530. get: function () {
  31531. return Material._CounterClockWiseSideOrientation;
  31532. },
  31533. enumerable: true,
  31534. configurable: true
  31535. });
  31536. Object.defineProperty(Material, "TextureDirtyFlag", {
  31537. /**
  31538. * Returns the dirty texture flag value.
  31539. */
  31540. get: function () {
  31541. return Material._TextureDirtyFlag;
  31542. },
  31543. enumerable: true,
  31544. configurable: true
  31545. });
  31546. Object.defineProperty(Material, "LightDirtyFlag", {
  31547. /**
  31548. * Returns the dirty light flag value.
  31549. */
  31550. get: function () {
  31551. return Material._LightDirtyFlag;
  31552. },
  31553. enumerable: true,
  31554. configurable: true
  31555. });
  31556. Object.defineProperty(Material, "FresnelDirtyFlag", {
  31557. /**
  31558. * Returns the dirty fresnel flag value.
  31559. */
  31560. get: function () {
  31561. return Material._FresnelDirtyFlag;
  31562. },
  31563. enumerable: true,
  31564. configurable: true
  31565. });
  31566. Object.defineProperty(Material, "AttributesDirtyFlag", {
  31567. /**
  31568. * Returns the dirty attributes flag value.
  31569. */
  31570. get: function () {
  31571. return Material._AttributesDirtyFlag;
  31572. },
  31573. enumerable: true,
  31574. configurable: true
  31575. });
  31576. Object.defineProperty(Material, "MiscDirtyFlag", {
  31577. /**
  31578. * Returns the dirty misc flag value.
  31579. */
  31580. get: function () {
  31581. return Material._MiscDirtyFlag;
  31582. },
  31583. enumerable: true,
  31584. configurable: true
  31585. });
  31586. Object.defineProperty(Material.prototype, "alpha", {
  31587. /**
  31588. * Gets the alpha value of the material.
  31589. */
  31590. get: function () {
  31591. return this._alpha;
  31592. },
  31593. /**
  31594. * Sets the alpha value of the material.
  31595. */
  31596. set: function (value) {
  31597. if (this._alpha === value) {
  31598. return;
  31599. }
  31600. this._alpha = value;
  31601. this.markAsDirty(Material.MiscDirtyFlag);
  31602. },
  31603. enumerable: true,
  31604. configurable: true
  31605. });
  31606. Object.defineProperty(Material.prototype, "backFaceCulling", {
  31607. /**
  31608. * Gets the back-face culling state.
  31609. */
  31610. get: function () {
  31611. return this._backFaceCulling;
  31612. },
  31613. /**
  31614. * Sets the back-face culling state.
  31615. */
  31616. set: function (value) {
  31617. if (this._backFaceCulling === value) {
  31618. return;
  31619. }
  31620. this._backFaceCulling = value;
  31621. this.markAsDirty(Material.TextureDirtyFlag);
  31622. },
  31623. enumerable: true,
  31624. configurable: true
  31625. });
  31626. Object.defineProperty(Material.prototype, "onDispose", {
  31627. /**
  31628. * Called during a dispose event.
  31629. */
  31630. set: function (callback) {
  31631. if (this._onDisposeObserver) {
  31632. this.onDisposeObservable.remove(this._onDisposeObserver);
  31633. }
  31634. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  31635. },
  31636. enumerable: true,
  31637. configurable: true
  31638. });
  31639. Object.defineProperty(Material.prototype, "onBind", {
  31640. /**
  31641. * Called during a bind event.
  31642. */
  31643. set: function (callback) {
  31644. if (this._onBindObserver) {
  31645. this.onBindObservable.remove(this._onBindObserver);
  31646. }
  31647. this._onBindObserver = this.onBindObservable.add(callback);
  31648. },
  31649. enumerable: true,
  31650. configurable: true
  31651. });
  31652. Object.defineProperty(Material.prototype, "alphaMode", {
  31653. /**
  31654. * Gets the value of the alpha mode.
  31655. */
  31656. get: function () {
  31657. return this._alphaMode;
  31658. },
  31659. /**
  31660. * Sets the value of the alpha mode.
  31661. */
  31662. set: function (value) {
  31663. if (this._alphaMode === value) {
  31664. return;
  31665. }
  31666. this._alphaMode = value;
  31667. this.markAsDirty(Material.TextureDirtyFlag);
  31668. },
  31669. enumerable: true,
  31670. configurable: true
  31671. });
  31672. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  31673. /**
  31674. * Gets the depth pre-pass value.
  31675. */
  31676. get: function () {
  31677. return this._needDepthPrePass;
  31678. },
  31679. /**
  31680. * Sets the need depth pre-pass value.
  31681. */
  31682. set: function (value) {
  31683. if (this._needDepthPrePass === value) {
  31684. return;
  31685. }
  31686. this._needDepthPrePass = value;
  31687. if (this._needDepthPrePass) {
  31688. this.checkReadyOnEveryCall = true;
  31689. }
  31690. },
  31691. enumerable: true,
  31692. configurable: true
  31693. });
  31694. Object.defineProperty(Material.prototype, "fogEnabled", {
  31695. /**
  31696. * Gets the value of the fog enabled state.
  31697. */
  31698. get: function () {
  31699. return this._fogEnabled;
  31700. },
  31701. /**
  31702. * Sets the state for enabling fog.
  31703. */
  31704. set: function (value) {
  31705. if (this._fogEnabled === value) {
  31706. return;
  31707. }
  31708. this._fogEnabled = value;
  31709. this.markAsDirty(Material.MiscDirtyFlag);
  31710. },
  31711. enumerable: true,
  31712. configurable: true
  31713. });
  31714. Object.defineProperty(Material.prototype, "wireframe", {
  31715. /**
  31716. * Gets a value specifying if wireframe mode is enabled.
  31717. */
  31718. get: function () {
  31719. switch (this._fillMode) {
  31720. case Material.WireFrameFillMode:
  31721. case Material.LineListDrawMode:
  31722. case Material.LineLoopDrawMode:
  31723. case Material.LineStripDrawMode:
  31724. return true;
  31725. }
  31726. return this._scene.forceWireframe;
  31727. },
  31728. /**
  31729. * Sets the state of wireframe mode.
  31730. */
  31731. set: function (value) {
  31732. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  31733. },
  31734. enumerable: true,
  31735. configurable: true
  31736. });
  31737. Object.defineProperty(Material.prototype, "pointsCloud", {
  31738. /**
  31739. * Gets the value specifying if point clouds are enabled.
  31740. */
  31741. get: function () {
  31742. switch (this._fillMode) {
  31743. case Material.PointFillMode:
  31744. case Material.PointListDrawMode:
  31745. return true;
  31746. }
  31747. return this._scene.forcePointsCloud;
  31748. },
  31749. /**
  31750. * Sets the state of point cloud mode.
  31751. */
  31752. set: function (value) {
  31753. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  31754. },
  31755. enumerable: true,
  31756. configurable: true
  31757. });
  31758. Object.defineProperty(Material.prototype, "fillMode", {
  31759. /**
  31760. * Gets the material fill mode.
  31761. */
  31762. get: function () {
  31763. return this._fillMode;
  31764. },
  31765. /**
  31766. * Sets the material fill mode.
  31767. */
  31768. set: function (value) {
  31769. if (this._fillMode === value) {
  31770. return;
  31771. }
  31772. this._fillMode = value;
  31773. this.markAsDirty(Material.MiscDirtyFlag);
  31774. },
  31775. enumerable: true,
  31776. configurable: true
  31777. });
  31778. /**
  31779. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31780. * subclasses should override adding information pertainent to themselves.
  31781. * @returns - String with material information.
  31782. */
  31783. Material.prototype.toString = function (fullDetails) {
  31784. var ret = "Name: " + this.name;
  31785. if (fullDetails) {
  31786. }
  31787. return ret;
  31788. };
  31789. /**
  31790. * Gets the class name of the material.
  31791. * @returns - String with the class name of the material.
  31792. */
  31793. Material.prototype.getClassName = function () {
  31794. return "Material";
  31795. };
  31796. Object.defineProperty(Material.prototype, "isFrozen", {
  31797. /**
  31798. * Specifies if updates for the material been locked.
  31799. */
  31800. get: function () {
  31801. return this.checkReadyOnlyOnce;
  31802. },
  31803. enumerable: true,
  31804. configurable: true
  31805. });
  31806. /**
  31807. * Locks updates for the material.
  31808. */
  31809. Material.prototype.freeze = function () {
  31810. this.checkReadyOnlyOnce = true;
  31811. };
  31812. /**
  31813. * Unlocks updates for the material.
  31814. */
  31815. Material.prototype.unfreeze = function () {
  31816. this.checkReadyOnlyOnce = false;
  31817. };
  31818. /**
  31819. * Specifies if the material is ready to be used.
  31820. * @param mesh - BJS mesh.
  31821. * @param useInstances - Specifies if instances should be used.
  31822. * @returns - Boolean indicating if the material is ready to be used.
  31823. */
  31824. Material.prototype.isReady = function (mesh, useInstances) {
  31825. return true;
  31826. };
  31827. /**
  31828. * Specifies that the submesh is ready to be used.
  31829. * @param mesh - BJS mesh.
  31830. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  31831. * @param useInstances - Specifies that instances should be used.
  31832. * @returns - boolean indicating that the submesh is ready or not.
  31833. */
  31834. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  31835. return false;
  31836. };
  31837. /**
  31838. * Returns the material effect.
  31839. * @returns - Nullable material effect.
  31840. */
  31841. Material.prototype.getEffect = function () {
  31842. return this._effect;
  31843. };
  31844. /**
  31845. * Returns the BJS scene.
  31846. * @returns - BJS Scene.
  31847. */
  31848. Material.prototype.getScene = function () {
  31849. return this._scene;
  31850. };
  31851. /**
  31852. * Specifies if the material will require alpha blending
  31853. * @returns - Boolean specifying if alpha blending is needed.
  31854. */
  31855. Material.prototype.needAlphaBlending = function () {
  31856. return (this.alpha < 1.0);
  31857. };
  31858. /**
  31859. * Specifies if the mesh will require alpha blending.
  31860. * @param mesh - BJS mesh.
  31861. * @returns - Boolean specifying if alpha blending is needed for the mesh.
  31862. */
  31863. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  31864. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  31865. };
  31866. /**
  31867. * Specifies if this material should be rendered in alpha test mode.
  31868. * @returns - Boolean specifying if an alpha test is needed.
  31869. */
  31870. Material.prototype.needAlphaTesting = function () {
  31871. return false;
  31872. };
  31873. /**
  31874. * Gets the texture used for the alpha test.
  31875. * @returns - Nullable alpha test texture.
  31876. */
  31877. Material.prototype.getAlphaTestTexture = function () {
  31878. return null;
  31879. };
  31880. /**
  31881. * Marks the material to indicate that it needs to be re-calculated.
  31882. */
  31883. Material.prototype.markDirty = function () {
  31884. this._wasPreviouslyReady = false;
  31885. };
  31886. Material.prototype._preBind = function (effect, overrideOrientation) {
  31887. if (overrideOrientation === void 0) { overrideOrientation = null; }
  31888. var engine = this._scene.getEngine();
  31889. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  31890. var reverse = orientation === Material.ClockWiseSideOrientation;
  31891. engine.enableEffect(effect ? effect : this._effect);
  31892. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  31893. return reverse;
  31894. };
  31895. /**
  31896. * Binds the material to the mesh.
  31897. * @param world - World transformation matrix.
  31898. * @param mesh - Mesh to bind the material to.
  31899. */
  31900. Material.prototype.bind = function (world, mesh) {
  31901. };
  31902. /**
  31903. * Binds the submesh to the material.
  31904. * @param world - World transformation matrix.
  31905. * @param mesh - Mesh containing the submesh.
  31906. * @param subMesh - Submesh to bind the material to.
  31907. */
  31908. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  31909. };
  31910. /**
  31911. * Binds the world matrix to the material.
  31912. * @param world - World transformation matrix.
  31913. */
  31914. Material.prototype.bindOnlyWorldMatrix = function (world) {
  31915. };
  31916. /**
  31917. * Binds the scene's uniform buffer to the effect.
  31918. * @param effect - Effect to bind to the scene uniform buffer.
  31919. * @param sceneUbo - Scene uniform buffer.
  31920. */
  31921. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  31922. sceneUbo.bindToEffect(effect, "Scene");
  31923. };
  31924. /**
  31925. * Binds the view matrix to the effect.
  31926. * @param effect - Effect to bind the view matrix to.
  31927. */
  31928. Material.prototype.bindView = function (effect) {
  31929. if (!this._useUBO) {
  31930. effect.setMatrix("view", this.getScene().getViewMatrix());
  31931. }
  31932. else {
  31933. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31934. }
  31935. };
  31936. /**
  31937. * Binds the view projection matrix to the effect.
  31938. * @param effect - Effect to bind the view projection matrix to.
  31939. */
  31940. Material.prototype.bindViewProjection = function (effect) {
  31941. if (!this._useUBO) {
  31942. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  31943. }
  31944. else {
  31945. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  31946. }
  31947. };
  31948. /**
  31949. * Specifies if material alpha testing should be turned on for the mesh.
  31950. * @param mesh - BJS mesh.
  31951. */
  31952. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  31953. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  31954. };
  31955. /**
  31956. * Processes to execute after binding the material to a mesh.
  31957. * @param mesh - BJS mesh.
  31958. */
  31959. Material.prototype._afterBind = function (mesh) {
  31960. this._scene._cachedMaterial = this;
  31961. if (mesh) {
  31962. this._scene._cachedVisibility = mesh.visibility;
  31963. }
  31964. else {
  31965. this._scene._cachedVisibility = 1;
  31966. }
  31967. if (mesh) {
  31968. this.onBindObservable.notifyObservers(mesh);
  31969. }
  31970. if (this.disableDepthWrite) {
  31971. var engine = this._scene.getEngine();
  31972. this._cachedDepthWriteState = engine.getDepthWrite();
  31973. engine.setDepthWrite(false);
  31974. }
  31975. };
  31976. /**
  31977. * Unbinds the material from the mesh.
  31978. */
  31979. Material.prototype.unbind = function () {
  31980. this.onUnBindObservable.notifyObservers(this);
  31981. if (this.disableDepthWrite) {
  31982. var engine = this._scene.getEngine();
  31983. engine.setDepthWrite(this._cachedDepthWriteState);
  31984. }
  31985. };
  31986. /**
  31987. * Gets the active textures from the material.
  31988. * @returns - Array of textures.
  31989. */
  31990. Material.prototype.getActiveTextures = function () {
  31991. return [];
  31992. };
  31993. /**
  31994. * Specifies if the material uses a texture.
  31995. * @param texture - Texture to check against the material.
  31996. * @returns - Boolean specifying if the material uses the texture.
  31997. */
  31998. Material.prototype.hasTexture = function (texture) {
  31999. return false;
  32000. };
  32001. /**
  32002. * Makes a duplicate of the material, and gives it a new name.
  32003. * @param name - Name to call the duplicated material.
  32004. * @returns - Nullable cloned material
  32005. */
  32006. Material.prototype.clone = function (name) {
  32007. return null;
  32008. };
  32009. /**
  32010. * Gets the meshes bound to the material.
  32011. * @returns - Array of meshes bound to the material.
  32012. */
  32013. Material.prototype.getBindedMeshes = function () {
  32014. var result = new Array();
  32015. for (var index = 0; index < this._scene.meshes.length; index++) {
  32016. var mesh = this._scene.meshes[index];
  32017. if (mesh.material === this) {
  32018. result.push(mesh);
  32019. }
  32020. }
  32021. return result;
  32022. };
  32023. /**
  32024. * Force shader compilation
  32025. * @param mesh - BJS mesh.
  32026. * @param onCompiled - function to execute once the material is compiled.
  32027. * @param options - options to pass to this function.
  32028. */
  32029. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  32030. var _this = this;
  32031. var localOptions = __assign({ clipPlane: false }, options);
  32032. var subMesh = new BABYLON.BaseSubMesh();
  32033. var scene = this.getScene();
  32034. var checkReady = function () {
  32035. if (!_this._scene || !_this._scene.getEngine()) {
  32036. return;
  32037. }
  32038. if (subMesh._materialDefines) {
  32039. subMesh._materialDefines._renderId = -1;
  32040. }
  32041. var clipPlaneState = scene.clipPlane;
  32042. if (localOptions.clipPlane) {
  32043. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  32044. }
  32045. if (_this.storeEffectOnSubMeshes) {
  32046. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  32047. if (onCompiled) {
  32048. onCompiled(_this);
  32049. }
  32050. }
  32051. else {
  32052. setTimeout(checkReady, 16);
  32053. }
  32054. }
  32055. else {
  32056. if (_this.isReady(mesh)) {
  32057. if (onCompiled) {
  32058. onCompiled(_this);
  32059. }
  32060. }
  32061. else {
  32062. setTimeout(checkReady, 16);
  32063. }
  32064. }
  32065. if (localOptions.clipPlane) {
  32066. scene.clipPlane = clipPlaneState;
  32067. }
  32068. };
  32069. checkReady();
  32070. };
  32071. /**
  32072. * Force shader compilation.
  32073. * @param mesh The mesh that will use this material
  32074. * @param options Additional options for compiling the shaders
  32075. * @returns A promise that resolves when the compilation completes
  32076. */
  32077. Material.prototype.forceCompilationAsync = function (mesh, options) {
  32078. var _this = this;
  32079. return new Promise(function (resolve) {
  32080. _this.forceCompilation(mesh, function () {
  32081. resolve();
  32082. }, options);
  32083. });
  32084. };
  32085. /**
  32086. * Marks a define in the material to indicate that it needs to be re-computed.
  32087. * @param flag - Material define flag.
  32088. */
  32089. Material.prototype.markAsDirty = function (flag) {
  32090. if (flag & Material.TextureDirtyFlag) {
  32091. this._markAllSubMeshesAsTexturesDirty();
  32092. }
  32093. if (flag & Material.LightDirtyFlag) {
  32094. this._markAllSubMeshesAsLightsDirty();
  32095. }
  32096. if (flag & Material.FresnelDirtyFlag) {
  32097. this._markAllSubMeshesAsFresnelDirty();
  32098. }
  32099. if (flag & Material.AttributesDirtyFlag) {
  32100. this._markAllSubMeshesAsAttributesDirty();
  32101. }
  32102. if (flag & Material.MiscDirtyFlag) {
  32103. this._markAllSubMeshesAsMiscDirty();
  32104. }
  32105. this.getScene().resetCachedMaterial();
  32106. };
  32107. /**
  32108. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated.
  32109. * @param func - function which checks material defines against the submeshes.
  32110. */
  32111. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  32112. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  32113. var mesh = _a[_i];
  32114. if (!mesh.subMeshes) {
  32115. continue;
  32116. }
  32117. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  32118. var subMesh = _c[_b];
  32119. if (subMesh.getMaterial() !== this) {
  32120. continue;
  32121. }
  32122. if (!subMesh._materialDefines) {
  32123. continue;
  32124. }
  32125. func(subMesh._materialDefines);
  32126. }
  32127. }
  32128. };
  32129. /**
  32130. * Indicates that image processing needs to be re-calculated for all submeshes.
  32131. */
  32132. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  32133. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  32134. };
  32135. /**
  32136. * Indicates that textures need to be re-calculated for all submeshes.
  32137. */
  32138. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  32139. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  32140. };
  32141. /**
  32142. * Indicates that fresnel needs to be re-calculated for all submeshes.
  32143. */
  32144. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  32145. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  32146. };
  32147. /**
  32148. * Indicates that fresnel and misc need to be re-calculated for all submeshes.
  32149. */
  32150. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  32151. this._markAllSubMeshesAsDirty(function (defines) {
  32152. defines.markAsFresnelDirty();
  32153. defines.markAsMiscDirty();
  32154. });
  32155. };
  32156. /**
  32157. * Indicates that lights need to be re-calculated for all submeshes.
  32158. */
  32159. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  32160. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  32161. };
  32162. /**
  32163. * Indicates that attributes need to be re-calculated for all submeshes.
  32164. */
  32165. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  32166. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  32167. };
  32168. /**
  32169. * Indicates that misc needs to be re-calculated for all submeshes.
  32170. */
  32171. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  32172. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  32173. };
  32174. /**
  32175. * Indicates that textures and misc need to be re-calculated for all submeshes.
  32176. */
  32177. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  32178. this._markAllSubMeshesAsDirty(function (defines) {
  32179. defines.markAsTexturesDirty();
  32180. defines.markAsMiscDirty();
  32181. });
  32182. };
  32183. /**
  32184. * Disposes the material.
  32185. * @param forceDisposeEffect - Specifies if effects should be force disposed.
  32186. * @param forceDisposeTextures - Specifies if textures should be force disposed.
  32187. */
  32188. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  32189. // Animations
  32190. this.getScene().stopAnimation(this);
  32191. this.getScene().freeProcessedMaterials();
  32192. // Remove from scene
  32193. var index = this._scene.materials.indexOf(this);
  32194. if (index >= 0) {
  32195. this._scene.materials.splice(index, 1);
  32196. }
  32197. // Remove from meshes
  32198. for (index = 0; index < this._scene.meshes.length; index++) {
  32199. var mesh = this._scene.meshes[index];
  32200. if (mesh.material === this) {
  32201. mesh.material = null;
  32202. if (mesh.geometry) {
  32203. var geometry = (mesh.geometry);
  32204. if (this.storeEffectOnSubMeshes) {
  32205. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  32206. var subMesh = _a[_i];
  32207. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  32208. if (forceDisposeEffect && subMesh._materialEffect) {
  32209. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  32210. }
  32211. }
  32212. }
  32213. else {
  32214. geometry._releaseVertexArrayObject(this._effect);
  32215. }
  32216. }
  32217. }
  32218. }
  32219. this._uniformBuffer.dispose();
  32220. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  32221. if (forceDisposeEffect && this._effect) {
  32222. if (!this.storeEffectOnSubMeshes) {
  32223. this._scene.getEngine()._releaseEffect(this._effect);
  32224. }
  32225. this._effect = null;
  32226. }
  32227. // Callback
  32228. this.onDisposeObservable.notifyObservers(this);
  32229. this.onDisposeObservable.clear();
  32230. this.onBindObservable.clear();
  32231. this.onUnBindObservable.clear();
  32232. };
  32233. /**
  32234. * Serializes this material.
  32235. * @returns - serialized material object.
  32236. */
  32237. Material.prototype.serialize = function () {
  32238. return BABYLON.SerializationHelper.Serialize(this);
  32239. };
  32240. /**
  32241. * Creates a MultiMaterial from parse MultiMaterial data.
  32242. * @param parsedMultiMaterial - Parsed MultiMaterial data.
  32243. * @param scene - BJS scene.
  32244. * @returns - MultiMaterial.
  32245. */
  32246. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  32247. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  32248. multiMaterial.id = parsedMultiMaterial.id;
  32249. if (BABYLON.Tags) {
  32250. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  32251. }
  32252. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  32253. var subMatId = parsedMultiMaterial.materials[matIndex];
  32254. if (subMatId) {
  32255. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  32256. }
  32257. else {
  32258. multiMaterial.subMaterials.push(null);
  32259. }
  32260. }
  32261. return multiMaterial;
  32262. };
  32263. /**
  32264. * Creates a material from parsed material data.
  32265. * @param parsedMaterial - Parsed material data.
  32266. * @param scene - BJS scene.
  32267. * @param rootUrl - Root URL containing the material information.
  32268. * @returns - Parsed material.
  32269. */
  32270. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  32271. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  32272. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  32273. }
  32274. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  32275. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  32276. if (!BABYLON.LegacyPBRMaterial) {
  32277. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  32278. return;
  32279. }
  32280. }
  32281. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  32282. return materialType.Parse(parsedMaterial, scene, rootUrl);
  32283. ;
  32284. };
  32285. // Triangle views
  32286. Material._TriangleFillMode = 0;
  32287. Material._WireFrameFillMode = 1;
  32288. Material._PointFillMode = 2;
  32289. // Draw modes
  32290. Material._PointListDrawMode = 3;
  32291. Material._LineListDrawMode = 4;
  32292. Material._LineLoopDrawMode = 5;
  32293. Material._LineStripDrawMode = 6;
  32294. Material._TriangleStripDrawMode = 7;
  32295. Material._TriangleFanDrawMode = 8;
  32296. /**
  32297. * Stores the clock-wise side orientation.
  32298. */
  32299. Material._ClockWiseSideOrientation = 0;
  32300. /**
  32301. * Stores the counter clock-wise side orientation.
  32302. */
  32303. Material._CounterClockWiseSideOrientation = 1;
  32304. /**
  32305. * The dirty texture flag value.
  32306. */
  32307. Material._TextureDirtyFlag = 1;
  32308. /**
  32309. * The dirty light flag value.
  32310. */
  32311. Material._LightDirtyFlag = 2;
  32312. /**
  32313. * The dirty fresnel flag value.
  32314. */
  32315. Material._FresnelDirtyFlag = 4;
  32316. /**
  32317. * The dirty attribute flag value.
  32318. */
  32319. Material._AttributesDirtyFlag = 8;
  32320. /**
  32321. * The dirty misc flag value.
  32322. */
  32323. Material._MiscDirtyFlag = 16;
  32324. __decorate([
  32325. BABYLON.serialize()
  32326. ], Material.prototype, "id", void 0);
  32327. __decorate([
  32328. BABYLON.serialize()
  32329. ], Material.prototype, "name", void 0);
  32330. __decorate([
  32331. BABYLON.serialize()
  32332. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  32333. __decorate([
  32334. BABYLON.serialize()
  32335. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  32336. __decorate([
  32337. BABYLON.serialize()
  32338. ], Material.prototype, "state", void 0);
  32339. __decorate([
  32340. BABYLON.serialize("alpha")
  32341. ], Material.prototype, "_alpha", void 0);
  32342. __decorate([
  32343. BABYLON.serialize("backFaceCulling")
  32344. ], Material.prototype, "_backFaceCulling", void 0);
  32345. __decorate([
  32346. BABYLON.serialize()
  32347. ], Material.prototype, "sideOrientation", void 0);
  32348. __decorate([
  32349. BABYLON.serialize("alphaMode")
  32350. ], Material.prototype, "_alphaMode", void 0);
  32351. __decorate([
  32352. BABYLON.serialize()
  32353. ], Material.prototype, "_needDepthPrePass", void 0);
  32354. __decorate([
  32355. BABYLON.serialize()
  32356. ], Material.prototype, "disableDepthWrite", void 0);
  32357. __decorate([
  32358. BABYLON.serialize()
  32359. ], Material.prototype, "forceDepthWrite", void 0);
  32360. __decorate([
  32361. BABYLON.serialize()
  32362. ], Material.prototype, "separateCullingPass", void 0);
  32363. __decorate([
  32364. BABYLON.serialize("fogEnabled")
  32365. ], Material.prototype, "_fogEnabled", void 0);
  32366. __decorate([
  32367. BABYLON.serialize()
  32368. ], Material.prototype, "pointSize", void 0);
  32369. __decorate([
  32370. BABYLON.serialize()
  32371. ], Material.prototype, "zOffset", void 0);
  32372. __decorate([
  32373. BABYLON.serialize()
  32374. ], Material.prototype, "wireframe", null);
  32375. __decorate([
  32376. BABYLON.serialize()
  32377. ], Material.prototype, "pointsCloud", null);
  32378. __decorate([
  32379. BABYLON.serialize()
  32380. ], Material.prototype, "fillMode", null);
  32381. return Material;
  32382. }());
  32383. BABYLON.Material = Material;
  32384. })(BABYLON || (BABYLON = {}));
  32385. //# sourceMappingURL=babylon.material.js.map
  32386. "use strict";
  32387. var BABYLON;
  32388. (function (BABYLON) {
  32389. var UniformBuffer = /** @class */ (function () {
  32390. /**
  32391. * Uniform buffer objects.
  32392. *
  32393. * Handles blocks of uniform on the GPU.
  32394. *
  32395. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  32396. *
  32397. * For more information, please refer to :
  32398. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  32399. */
  32400. function UniformBuffer(engine, data, dynamic) {
  32401. this._engine = engine;
  32402. this._noUBO = !engine.supportsUniformBuffers;
  32403. this._dynamic = dynamic;
  32404. this._data = data || [];
  32405. this._uniformLocations = {};
  32406. this._uniformSizes = {};
  32407. this._uniformLocationPointer = 0;
  32408. this._needSync = false;
  32409. if (this._noUBO) {
  32410. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  32411. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  32412. this.updateFloat = this._updateFloatForEffect;
  32413. this.updateFloat2 = this._updateFloat2ForEffect;
  32414. this.updateFloat3 = this._updateFloat3ForEffect;
  32415. this.updateFloat4 = this._updateFloat4ForEffect;
  32416. this.updateMatrix = this._updateMatrixForEffect;
  32417. this.updateVector3 = this._updateVector3ForEffect;
  32418. this.updateVector4 = this._updateVector4ForEffect;
  32419. this.updateColor3 = this._updateColor3ForEffect;
  32420. this.updateColor4 = this._updateColor4ForEffect;
  32421. }
  32422. else {
  32423. this._engine._uniformBuffers.push(this);
  32424. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  32425. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  32426. this.updateFloat = this._updateFloatForUniform;
  32427. this.updateFloat2 = this._updateFloat2ForUniform;
  32428. this.updateFloat3 = this._updateFloat3ForUniform;
  32429. this.updateFloat4 = this._updateFloat4ForUniform;
  32430. this.updateMatrix = this._updateMatrixForUniform;
  32431. this.updateVector3 = this._updateVector3ForUniform;
  32432. this.updateVector4 = this._updateVector4ForUniform;
  32433. this.updateColor3 = this._updateColor3ForUniform;
  32434. this.updateColor4 = this._updateColor4ForUniform;
  32435. }
  32436. }
  32437. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  32438. // Properties
  32439. /**
  32440. * Indicates if the buffer is using the WebGL2 UBO implementation,
  32441. * or just falling back on setUniformXXX calls.
  32442. */
  32443. get: function () {
  32444. return !this._noUBO;
  32445. },
  32446. enumerable: true,
  32447. configurable: true
  32448. });
  32449. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  32450. /**
  32451. * Indicates if the WebGL underlying uniform buffer is in sync
  32452. * with the javascript cache data.
  32453. */
  32454. get: function () {
  32455. return !this._needSync;
  32456. },
  32457. enumerable: true,
  32458. configurable: true
  32459. });
  32460. /**
  32461. * Indicates if the WebGL underlying uniform buffer is dynamic.
  32462. * Also, a dynamic UniformBuffer will disable cache verification and always
  32463. * update the underlying WebGL uniform buffer to the GPU.
  32464. */
  32465. UniformBuffer.prototype.isDynamic = function () {
  32466. return this._dynamic !== undefined;
  32467. };
  32468. /**
  32469. * The data cache on JS side.
  32470. */
  32471. UniformBuffer.prototype.getData = function () {
  32472. return this._bufferData;
  32473. };
  32474. /**
  32475. * The underlying WebGL Uniform buffer.
  32476. */
  32477. UniformBuffer.prototype.getBuffer = function () {
  32478. return this._buffer;
  32479. };
  32480. /**
  32481. * std140 layout specifies how to align data within an UBO structure.
  32482. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  32483. * for specs.
  32484. */
  32485. UniformBuffer.prototype._fillAlignment = function (size) {
  32486. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  32487. // and 4x4 matrices
  32488. // TODO : change if other types are used
  32489. var alignment;
  32490. if (size <= 2) {
  32491. alignment = size;
  32492. }
  32493. else {
  32494. alignment = 4;
  32495. }
  32496. if ((this._uniformLocationPointer % alignment) !== 0) {
  32497. var oldPointer = this._uniformLocationPointer;
  32498. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  32499. var diff = this._uniformLocationPointer - oldPointer;
  32500. for (var i = 0; i < diff; i++) {
  32501. this._data.push(0);
  32502. }
  32503. }
  32504. };
  32505. /**
  32506. * Adds an uniform in the buffer.
  32507. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  32508. * for the layout to be correct !
  32509. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32510. * @param {number|number[]} size Data size, or data directly.
  32511. */
  32512. UniformBuffer.prototype.addUniform = function (name, size) {
  32513. if (this._noUBO) {
  32514. return;
  32515. }
  32516. if (this._uniformLocations[name] !== undefined) {
  32517. // Already existing uniform
  32518. return;
  32519. }
  32520. // This function must be called in the order of the shader layout !
  32521. // size can be the size of the uniform, or data directly
  32522. var data;
  32523. if (size instanceof Array) {
  32524. data = size;
  32525. size = data.length;
  32526. }
  32527. else {
  32528. size = size;
  32529. data = [];
  32530. // Fill with zeros
  32531. for (var i = 0; i < size; i++) {
  32532. data.push(0);
  32533. }
  32534. }
  32535. this._fillAlignment(size);
  32536. this._uniformSizes[name] = size;
  32537. this._uniformLocations[name] = this._uniformLocationPointer;
  32538. this._uniformLocationPointer += size;
  32539. for (var i = 0; i < size; i++) {
  32540. this._data.push(data[i]);
  32541. }
  32542. this._needSync = true;
  32543. };
  32544. /**
  32545. * Wrapper for addUniform.
  32546. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32547. * @param {Matrix} mat A 4x4 matrix.
  32548. */
  32549. UniformBuffer.prototype.addMatrix = function (name, mat) {
  32550. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  32551. };
  32552. /**
  32553. * Wrapper for addUniform.
  32554. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32555. * @param {number} x
  32556. * @param {number} y
  32557. */
  32558. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  32559. var temp = [x, y];
  32560. this.addUniform(name, temp);
  32561. };
  32562. /**
  32563. * Wrapper for addUniform.
  32564. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32565. * @param {number} x
  32566. * @param {number} y
  32567. * @param {number} z
  32568. */
  32569. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  32570. var temp = [x, y, z];
  32571. this.addUniform(name, temp);
  32572. };
  32573. /**
  32574. * Wrapper for addUniform.
  32575. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32576. * @param {Color3} color
  32577. */
  32578. UniformBuffer.prototype.addColor3 = function (name, color) {
  32579. var temp = new Array();
  32580. color.toArray(temp);
  32581. this.addUniform(name, temp);
  32582. };
  32583. /**
  32584. * Wrapper for addUniform.
  32585. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32586. * @param {Color3} color
  32587. * @param {number} alpha
  32588. */
  32589. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  32590. var temp = new Array();
  32591. color.toArray(temp);
  32592. temp.push(alpha);
  32593. this.addUniform(name, temp);
  32594. };
  32595. /**
  32596. * Wrapper for addUniform.
  32597. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32598. * @param {Vector3} vector
  32599. */
  32600. UniformBuffer.prototype.addVector3 = function (name, vector) {
  32601. var temp = new Array();
  32602. vector.toArray(temp);
  32603. this.addUniform(name, temp);
  32604. };
  32605. /**
  32606. * Wrapper for addUniform.
  32607. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32608. */
  32609. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  32610. this.addUniform(name, 12);
  32611. };
  32612. /**
  32613. * Wrapper for addUniform.
  32614. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  32615. */
  32616. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  32617. this.addUniform(name, 8);
  32618. };
  32619. /**
  32620. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  32621. */
  32622. UniformBuffer.prototype.create = function () {
  32623. if (this._noUBO) {
  32624. return;
  32625. }
  32626. if (this._buffer) {
  32627. return; // nothing to do
  32628. }
  32629. // See spec, alignment must be filled as a vec4
  32630. this._fillAlignment(4);
  32631. this._bufferData = new Float32Array(this._data);
  32632. this._rebuild();
  32633. this._needSync = true;
  32634. };
  32635. UniformBuffer.prototype._rebuild = function () {
  32636. if (this._noUBO) {
  32637. return;
  32638. }
  32639. if (this._dynamic) {
  32640. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  32641. }
  32642. else {
  32643. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  32644. }
  32645. };
  32646. /**
  32647. * Updates the WebGL Uniform Buffer on the GPU.
  32648. * If the `dynamic` flag is set to true, no cache comparison is done.
  32649. * Otherwise, the buffer will be updated only if the cache differs.
  32650. */
  32651. UniformBuffer.prototype.update = function () {
  32652. if (!this._buffer) {
  32653. this.create();
  32654. return;
  32655. }
  32656. if (!this._dynamic && !this._needSync) {
  32657. return;
  32658. }
  32659. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  32660. this._needSync = false;
  32661. };
  32662. /**
  32663. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  32664. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32665. * @param {number[]|Float32Array} data Flattened data
  32666. * @param {number} size Size of the data.
  32667. */
  32668. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  32669. var location = this._uniformLocations[uniformName];
  32670. if (location === undefined) {
  32671. if (this._buffer) {
  32672. // Cannot add an uniform if the buffer is already created
  32673. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  32674. return;
  32675. }
  32676. this.addUniform(uniformName, size);
  32677. location = this._uniformLocations[uniformName];
  32678. }
  32679. if (!this._buffer) {
  32680. this.create();
  32681. }
  32682. if (!this._dynamic) {
  32683. // Cache for static uniform buffers
  32684. var changed = false;
  32685. for (var i = 0; i < size; i++) {
  32686. if (this._bufferData[location + i] !== data[i]) {
  32687. changed = true;
  32688. this._bufferData[location + i] = data[i];
  32689. }
  32690. }
  32691. this._needSync = this._needSync || changed;
  32692. }
  32693. else {
  32694. // No cache for dynamic
  32695. for (var i = 0; i < size; i++) {
  32696. this._bufferData[location + i] = data[i];
  32697. }
  32698. }
  32699. };
  32700. // Update methods
  32701. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  32702. // To match std140, matrix must be realigned
  32703. for (var i = 0; i < 3; i++) {
  32704. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  32705. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  32706. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  32707. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32708. }
  32709. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  32710. };
  32711. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  32712. this._currentEffect.setMatrix3x3(name, matrix);
  32713. };
  32714. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  32715. this._currentEffect.setMatrix2x2(name, matrix);
  32716. };
  32717. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  32718. // To match std140, matrix must be realigned
  32719. for (var i = 0; i < 2; i++) {
  32720. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  32721. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  32722. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  32723. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  32724. }
  32725. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  32726. };
  32727. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  32728. this._currentEffect.setFloat(name, x);
  32729. };
  32730. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  32731. UniformBuffer._tempBuffer[0] = x;
  32732. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  32733. };
  32734. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  32735. if (suffix === void 0) { suffix = ""; }
  32736. this._currentEffect.setFloat2(name + suffix, x, y);
  32737. };
  32738. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  32739. if (suffix === void 0) { suffix = ""; }
  32740. UniformBuffer._tempBuffer[0] = x;
  32741. UniformBuffer._tempBuffer[1] = y;
  32742. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  32743. };
  32744. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  32745. if (suffix === void 0) { suffix = ""; }
  32746. this._currentEffect.setFloat3(name + suffix, x, y, z);
  32747. };
  32748. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  32749. if (suffix === void 0) { suffix = ""; }
  32750. UniformBuffer._tempBuffer[0] = x;
  32751. UniformBuffer._tempBuffer[1] = y;
  32752. UniformBuffer._tempBuffer[2] = z;
  32753. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32754. };
  32755. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  32756. if (suffix === void 0) { suffix = ""; }
  32757. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  32758. };
  32759. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  32760. if (suffix === void 0) { suffix = ""; }
  32761. UniformBuffer._tempBuffer[0] = x;
  32762. UniformBuffer._tempBuffer[1] = y;
  32763. UniformBuffer._tempBuffer[2] = z;
  32764. UniformBuffer._tempBuffer[3] = w;
  32765. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32766. };
  32767. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  32768. this._currentEffect.setMatrix(name, mat);
  32769. };
  32770. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  32771. this.updateUniform(name, mat.toArray(), 16);
  32772. };
  32773. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  32774. this._currentEffect.setVector3(name, vector);
  32775. };
  32776. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  32777. vector.toArray(UniformBuffer._tempBuffer);
  32778. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32779. };
  32780. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  32781. this._currentEffect.setVector4(name, vector);
  32782. };
  32783. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  32784. vector.toArray(UniformBuffer._tempBuffer);
  32785. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32786. };
  32787. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  32788. if (suffix === void 0) { suffix = ""; }
  32789. this._currentEffect.setColor3(name + suffix, color);
  32790. };
  32791. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  32792. if (suffix === void 0) { suffix = ""; }
  32793. color.toArray(UniformBuffer._tempBuffer);
  32794. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  32795. };
  32796. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  32797. if (suffix === void 0) { suffix = ""; }
  32798. this._currentEffect.setColor4(name + suffix, color, alpha);
  32799. };
  32800. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  32801. if (suffix === void 0) { suffix = ""; }
  32802. color.toArray(UniformBuffer._tempBuffer);
  32803. UniformBuffer._tempBuffer[3] = alpha;
  32804. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  32805. };
  32806. /**
  32807. * Sets a sampler uniform on the effect.
  32808. * @param {string} name Name of the sampler.
  32809. * @param {Texture} texture
  32810. */
  32811. UniformBuffer.prototype.setTexture = function (name, texture) {
  32812. this._currentEffect.setTexture(name, texture);
  32813. };
  32814. /**
  32815. * Directly updates the value of the uniform in the cache AND on the GPU.
  32816. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  32817. * @param {number[]|Float32Array} data Flattened data
  32818. */
  32819. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  32820. this.updateUniform(uniformName, data, data.length);
  32821. this.update();
  32822. };
  32823. /**
  32824. * Binds this uniform buffer to an effect.
  32825. * @param {Effect} effect
  32826. * @param {string} name Name of the uniform block in the shader.
  32827. */
  32828. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  32829. this._currentEffect = effect;
  32830. if (this._noUBO || !this._buffer) {
  32831. return;
  32832. }
  32833. effect.bindUniformBuffer(this._buffer, name);
  32834. };
  32835. /**
  32836. * Disposes the uniform buffer.
  32837. */
  32838. UniformBuffer.prototype.dispose = function () {
  32839. if (this._noUBO) {
  32840. return;
  32841. }
  32842. var index = this._engine._uniformBuffers.indexOf(this);
  32843. if (index !== -1) {
  32844. this._engine._uniformBuffers.splice(index, 1);
  32845. }
  32846. if (!this._buffer) {
  32847. return;
  32848. }
  32849. if (this._engine._releaseBuffer(this._buffer)) {
  32850. this._buffer = null;
  32851. }
  32852. };
  32853. // Pool for avoiding memory leaks
  32854. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  32855. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  32856. return UniformBuffer;
  32857. }());
  32858. BABYLON.UniformBuffer = UniformBuffer;
  32859. })(BABYLON || (BABYLON = {}));
  32860. //# sourceMappingURL=babylon.uniformBuffer.js.map
  32861. "use strict";
  32862. var BABYLON;
  32863. (function (BABYLON) {
  32864. var VertexData = /** @class */ (function () {
  32865. function VertexData() {
  32866. }
  32867. VertexData.prototype.set = function (data, kind) {
  32868. switch (kind) {
  32869. case BABYLON.VertexBuffer.PositionKind:
  32870. this.positions = data;
  32871. break;
  32872. case BABYLON.VertexBuffer.NormalKind:
  32873. this.normals = data;
  32874. break;
  32875. case BABYLON.VertexBuffer.TangentKind:
  32876. this.tangents = data;
  32877. break;
  32878. case BABYLON.VertexBuffer.UVKind:
  32879. this.uvs = data;
  32880. break;
  32881. case BABYLON.VertexBuffer.UV2Kind:
  32882. this.uvs2 = data;
  32883. break;
  32884. case BABYLON.VertexBuffer.UV3Kind:
  32885. this.uvs3 = data;
  32886. break;
  32887. case BABYLON.VertexBuffer.UV4Kind:
  32888. this.uvs4 = data;
  32889. break;
  32890. case BABYLON.VertexBuffer.UV5Kind:
  32891. this.uvs5 = data;
  32892. break;
  32893. case BABYLON.VertexBuffer.UV6Kind:
  32894. this.uvs6 = data;
  32895. break;
  32896. case BABYLON.VertexBuffer.ColorKind:
  32897. this.colors = data;
  32898. break;
  32899. case BABYLON.VertexBuffer.MatricesIndicesKind:
  32900. this.matricesIndices = data;
  32901. break;
  32902. case BABYLON.VertexBuffer.MatricesWeightsKind:
  32903. this.matricesWeights = data;
  32904. break;
  32905. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  32906. this.matricesIndicesExtra = data;
  32907. break;
  32908. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  32909. this.matricesWeightsExtra = data;
  32910. break;
  32911. }
  32912. };
  32913. /**
  32914. * Associates the vertexData to the passed Mesh.
  32915. * Sets it as updatable or not (default `false`).
  32916. * Returns the VertexData.
  32917. */
  32918. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  32919. this._applyTo(mesh, updatable);
  32920. return this;
  32921. };
  32922. /**
  32923. * Associates the vertexData to the passed Geometry.
  32924. * Sets it as updatable or not (default `false`).
  32925. * Returns the VertexData.
  32926. */
  32927. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  32928. this._applyTo(geometry, updatable);
  32929. return this;
  32930. };
  32931. /**
  32932. * Updates the associated mesh.
  32933. * Returns the VertexData.
  32934. */
  32935. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  32936. this._update(mesh);
  32937. return this;
  32938. };
  32939. /**
  32940. * Updates the associated geometry.
  32941. * Returns the VertexData.
  32942. */
  32943. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  32944. this._update(geometry);
  32945. return this;
  32946. };
  32947. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  32948. if (updatable === void 0) { updatable = false; }
  32949. if (this.positions) {
  32950. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  32951. }
  32952. if (this.normals) {
  32953. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  32954. }
  32955. if (this.tangents) {
  32956. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  32957. }
  32958. if (this.uvs) {
  32959. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  32960. }
  32961. if (this.uvs2) {
  32962. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  32963. }
  32964. if (this.uvs3) {
  32965. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  32966. }
  32967. if (this.uvs4) {
  32968. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  32969. }
  32970. if (this.uvs5) {
  32971. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  32972. }
  32973. if (this.uvs6) {
  32974. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  32975. }
  32976. if (this.colors) {
  32977. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  32978. }
  32979. if (this.matricesIndices) {
  32980. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  32981. }
  32982. if (this.matricesWeights) {
  32983. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  32984. }
  32985. if (this.matricesIndicesExtra) {
  32986. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  32987. }
  32988. if (this.matricesWeightsExtra) {
  32989. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  32990. }
  32991. if (this.indices) {
  32992. meshOrGeometry.setIndices(this.indices, null, updatable);
  32993. }
  32994. return this;
  32995. };
  32996. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  32997. if (this.positions) {
  32998. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  32999. }
  33000. if (this.normals) {
  33001. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  33002. }
  33003. if (this.tangents) {
  33004. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  33005. }
  33006. if (this.uvs) {
  33007. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  33008. }
  33009. if (this.uvs2) {
  33010. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  33011. }
  33012. if (this.uvs3) {
  33013. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  33014. }
  33015. if (this.uvs4) {
  33016. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  33017. }
  33018. if (this.uvs5) {
  33019. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  33020. }
  33021. if (this.uvs6) {
  33022. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  33023. }
  33024. if (this.colors) {
  33025. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  33026. }
  33027. if (this.matricesIndices) {
  33028. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  33029. }
  33030. if (this.matricesWeights) {
  33031. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  33032. }
  33033. if (this.matricesIndicesExtra) {
  33034. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  33035. }
  33036. if (this.matricesWeightsExtra) {
  33037. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  33038. }
  33039. if (this.indices) {
  33040. meshOrGeometry.setIndices(this.indices, null);
  33041. }
  33042. return this;
  33043. };
  33044. /**
  33045. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  33046. * Returns the VertexData.
  33047. */
  33048. VertexData.prototype.transform = function (matrix) {
  33049. var transformed = BABYLON.Vector3.Zero();
  33050. var index;
  33051. if (this.positions) {
  33052. var position = BABYLON.Vector3.Zero();
  33053. for (index = 0; index < this.positions.length; index += 3) {
  33054. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  33055. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  33056. this.positions[index] = transformed.x;
  33057. this.positions[index + 1] = transformed.y;
  33058. this.positions[index + 2] = transformed.z;
  33059. }
  33060. }
  33061. if (this.normals) {
  33062. var normal = BABYLON.Vector3.Zero();
  33063. for (index = 0; index < this.normals.length; index += 3) {
  33064. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  33065. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  33066. this.normals[index] = transformed.x;
  33067. this.normals[index + 1] = transformed.y;
  33068. this.normals[index + 2] = transformed.z;
  33069. }
  33070. }
  33071. if (this.tangents) {
  33072. var tangent = BABYLON.Vector4.Zero();
  33073. var tangentTransformed = BABYLON.Vector4.Zero();
  33074. for (index = 0; index < this.tangents.length; index += 4) {
  33075. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  33076. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  33077. this.tangents[index] = tangentTransformed.x;
  33078. this.tangents[index + 1] = tangentTransformed.y;
  33079. this.tangents[index + 2] = tangentTransformed.z;
  33080. this.tangents[index + 3] = tangentTransformed.w;
  33081. }
  33082. }
  33083. return this;
  33084. };
  33085. /**
  33086. * Merges the passed VertexData into the current one.
  33087. * Returns the modified VertexData.
  33088. */
  33089. VertexData.prototype.merge = function (other) {
  33090. this._validate();
  33091. other._validate();
  33092. if (!this.normals !== !other.normals ||
  33093. !this.tangents !== !other.tangents ||
  33094. !this.uvs !== !other.uvs ||
  33095. !this.uvs2 !== !other.uvs2 ||
  33096. !this.uvs3 !== !other.uvs3 ||
  33097. !this.uvs4 !== !other.uvs4 ||
  33098. !this.uvs5 !== !other.uvs5 ||
  33099. !this.uvs6 !== !other.uvs6 ||
  33100. !this.colors !== !other.colors ||
  33101. !this.matricesIndices !== !other.matricesIndices ||
  33102. !this.matricesWeights !== !other.matricesWeights ||
  33103. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  33104. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  33105. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  33106. }
  33107. if (other.indices) {
  33108. if (!this.indices) {
  33109. this.indices = [];
  33110. }
  33111. var offset = this.positions ? this.positions.length / 3 : 0;
  33112. for (var index = 0; index < other.indices.length; index++) {
  33113. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  33114. this.indices.push(other.indices[index] + offset);
  33115. }
  33116. }
  33117. this.positions = this._mergeElement(this.positions, other.positions);
  33118. this.normals = this._mergeElement(this.normals, other.normals);
  33119. this.tangents = this._mergeElement(this.tangents, other.tangents);
  33120. this.uvs = this._mergeElement(this.uvs, other.uvs);
  33121. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  33122. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  33123. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  33124. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  33125. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  33126. this.colors = this._mergeElement(this.colors, other.colors);
  33127. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  33128. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  33129. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  33130. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  33131. return this;
  33132. };
  33133. VertexData.prototype._mergeElement = function (source, other) {
  33134. if (!source) {
  33135. return other;
  33136. }
  33137. if (!other) {
  33138. return source;
  33139. }
  33140. var len = other.length + source.length;
  33141. var isSrcTypedArray = source instanceof Float32Array;
  33142. var isOthTypedArray = other instanceof Float32Array;
  33143. // use non-loop method when the source is Float32Array
  33144. if (isSrcTypedArray) {
  33145. var ret32 = new Float32Array(len);
  33146. ret32.set(source);
  33147. ret32.set(other, source.length);
  33148. return ret32;
  33149. // source is number[], when other is also use concat
  33150. }
  33151. else if (!isOthTypedArray) {
  33152. return source.concat(other);
  33153. // source is a number[], but other is a Float32Array, loop required
  33154. }
  33155. else {
  33156. var ret = source.slice(0); // copy source to a separate array
  33157. for (var i = 0, len = other.length; i < len; i++) {
  33158. ret.push(other[i]);
  33159. }
  33160. return ret;
  33161. }
  33162. };
  33163. VertexData.prototype._validate = function () {
  33164. if (!this.positions) {
  33165. throw new Error("Positions are required");
  33166. }
  33167. var getElementCount = function (kind, values) {
  33168. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  33169. if ((values.length % stride) !== 0) {
  33170. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  33171. }
  33172. return values.length / stride;
  33173. };
  33174. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  33175. var validateElementCount = function (kind, values) {
  33176. var elementCount = getElementCount(kind, values);
  33177. if (elementCount !== positionsElementCount) {
  33178. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  33179. }
  33180. };
  33181. if (this.normals)
  33182. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  33183. if (this.tangents)
  33184. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  33185. if (this.uvs)
  33186. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  33187. if (this.uvs2)
  33188. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  33189. if (this.uvs3)
  33190. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  33191. if (this.uvs4)
  33192. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  33193. if (this.uvs5)
  33194. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  33195. if (this.uvs6)
  33196. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  33197. if (this.colors)
  33198. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  33199. if (this.matricesIndices)
  33200. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  33201. if (this.matricesWeights)
  33202. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  33203. if (this.matricesIndicesExtra)
  33204. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  33205. if (this.matricesWeightsExtra)
  33206. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  33207. };
  33208. /**
  33209. * Serializes the VertexData.
  33210. * Returns a serialized object.
  33211. */
  33212. VertexData.prototype.serialize = function () {
  33213. var serializationObject = this.serialize();
  33214. if (this.positions) {
  33215. serializationObject.positions = this.positions;
  33216. }
  33217. if (this.normals) {
  33218. serializationObject.normals = this.normals;
  33219. }
  33220. if (this.tangents) {
  33221. serializationObject.tangents = this.tangents;
  33222. }
  33223. if (this.uvs) {
  33224. serializationObject.uvs = this.uvs;
  33225. }
  33226. if (this.uvs2) {
  33227. serializationObject.uvs2 = this.uvs2;
  33228. }
  33229. if (this.uvs3) {
  33230. serializationObject.uvs3 = this.uvs3;
  33231. }
  33232. if (this.uvs4) {
  33233. serializationObject.uvs4 = this.uvs4;
  33234. }
  33235. if (this.uvs5) {
  33236. serializationObject.uvs5 = this.uvs5;
  33237. }
  33238. if (this.uvs6) {
  33239. serializationObject.uvs6 = this.uvs6;
  33240. }
  33241. if (this.colors) {
  33242. serializationObject.colors = this.colors;
  33243. }
  33244. if (this.matricesIndices) {
  33245. serializationObject.matricesIndices = this.matricesIndices;
  33246. serializationObject.matricesIndices._isExpanded = true;
  33247. }
  33248. if (this.matricesWeights) {
  33249. serializationObject.matricesWeights = this.matricesWeights;
  33250. }
  33251. if (this.matricesIndicesExtra) {
  33252. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  33253. serializationObject.matricesIndicesExtra._isExpanded = true;
  33254. }
  33255. if (this.matricesWeightsExtra) {
  33256. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  33257. }
  33258. serializationObject.indices = this.indices;
  33259. return serializationObject;
  33260. };
  33261. // Statics
  33262. /**
  33263. * Returns the object VertexData associated to the passed mesh.
  33264. */
  33265. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  33266. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  33267. };
  33268. /**
  33269. * Returns the object VertexData associated to the passed geometry.
  33270. */
  33271. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  33272. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  33273. };
  33274. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  33275. var result = new VertexData();
  33276. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33277. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  33278. }
  33279. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33280. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  33281. }
  33282. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  33283. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  33284. }
  33285. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33286. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  33287. }
  33288. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33289. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  33290. }
  33291. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  33292. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  33293. }
  33294. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  33295. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  33296. }
  33297. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  33298. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  33299. }
  33300. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  33301. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  33302. }
  33303. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  33304. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  33305. }
  33306. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33307. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  33308. }
  33309. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33310. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  33311. }
  33312. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  33313. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  33314. }
  33315. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  33316. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  33317. }
  33318. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  33319. return result;
  33320. };
  33321. /**
  33322. * Creates the vertexData of the Ribbon.
  33323. */
  33324. VertexData.CreateRibbon = function (options) {
  33325. var pathArray = options.pathArray;
  33326. var closeArray = options.closeArray || false;
  33327. var closePath = options.closePath || false;
  33328. var invertUV = options.invertUV || false;
  33329. var defaultOffset = Math.floor(pathArray[0].length / 2);
  33330. var offset = options.offset || defaultOffset;
  33331. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  33332. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33333. var customUV = options.uvs;
  33334. var customColors = options.colors;
  33335. var positions = [];
  33336. var indices = [];
  33337. var normals = [];
  33338. var uvs = [];
  33339. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  33340. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  33341. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  33342. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  33343. var minlg; // minimal length among all paths from pathArray
  33344. var lg = []; // array of path lengths : nb of vertex per path
  33345. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  33346. var p; // path iterator
  33347. var i; // point iterator
  33348. var j; // point iterator
  33349. // if single path in pathArray
  33350. if (pathArray.length < 2) {
  33351. var ar1 = [];
  33352. var ar2 = [];
  33353. for (i = 0; i < pathArray[0].length - offset; i++) {
  33354. ar1.push(pathArray[0][i]);
  33355. ar2.push(pathArray[0][i + offset]);
  33356. }
  33357. pathArray = [ar1, ar2];
  33358. }
  33359. // positions and horizontal distances (u)
  33360. var idc = 0;
  33361. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  33362. var path;
  33363. var l;
  33364. minlg = pathArray[0].length;
  33365. var vectlg;
  33366. var dist;
  33367. for (p = 0; p < pathArray.length; p++) {
  33368. uTotalDistance[p] = 0;
  33369. us[p] = [0];
  33370. path = pathArray[p];
  33371. l = path.length;
  33372. minlg = (minlg < l) ? minlg : l;
  33373. j = 0;
  33374. while (j < l) {
  33375. positions.push(path[j].x, path[j].y, path[j].z);
  33376. if (j > 0) {
  33377. vectlg = path[j].subtract(path[j - 1]).length();
  33378. dist = vectlg + uTotalDistance[p];
  33379. us[p].push(dist);
  33380. uTotalDistance[p] = dist;
  33381. }
  33382. j++;
  33383. }
  33384. if (closePath) {
  33385. j--;
  33386. positions.push(path[0].x, path[0].y, path[0].z);
  33387. vectlg = path[j].subtract(path[0]).length();
  33388. dist = vectlg + uTotalDistance[p];
  33389. us[p].push(dist);
  33390. uTotalDistance[p] = dist;
  33391. }
  33392. lg[p] = l + closePathCorr;
  33393. idx[p] = idc;
  33394. idc += (l + closePathCorr);
  33395. }
  33396. // vertical distances (v)
  33397. var path1;
  33398. var path2;
  33399. var vertex1 = null;
  33400. var vertex2 = null;
  33401. for (i = 0; i < minlg + closePathCorr; i++) {
  33402. vTotalDistance[i] = 0;
  33403. vs[i] = [0];
  33404. for (p = 0; p < pathArray.length - 1; p++) {
  33405. path1 = pathArray[p];
  33406. path2 = pathArray[p + 1];
  33407. if (i === minlg) {
  33408. vertex1 = path1[0];
  33409. vertex2 = path2[0];
  33410. }
  33411. else {
  33412. vertex1 = path1[i];
  33413. vertex2 = path2[i];
  33414. }
  33415. vectlg = vertex2.subtract(vertex1).length();
  33416. dist = vectlg + vTotalDistance[i];
  33417. vs[i].push(dist);
  33418. vTotalDistance[i] = dist;
  33419. }
  33420. if (closeArray && vertex2 && vertex1) {
  33421. path1 = pathArray[p];
  33422. path2 = pathArray[0];
  33423. if (i === minlg) {
  33424. vertex2 = path2[0];
  33425. }
  33426. vectlg = vertex2.subtract(vertex1).length();
  33427. dist = vectlg + vTotalDistance[i];
  33428. vTotalDistance[i] = dist;
  33429. }
  33430. }
  33431. // uvs
  33432. var u;
  33433. var v;
  33434. if (customUV) {
  33435. for (p = 0; p < customUV.length; p++) {
  33436. uvs.push(customUV[p].x, customUV[p].y);
  33437. }
  33438. }
  33439. else {
  33440. for (p = 0; p < pathArray.length; p++) {
  33441. for (i = 0; i < minlg + closePathCorr; i++) {
  33442. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  33443. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  33444. if (invertUV) {
  33445. uvs.push(v, u);
  33446. }
  33447. else {
  33448. uvs.push(u, v);
  33449. }
  33450. }
  33451. }
  33452. }
  33453. // indices
  33454. p = 0; // path index
  33455. var pi = 0; // positions array index
  33456. var l1 = lg[p] - 1; // path1 length
  33457. var l2 = lg[p + 1] - 1; // path2 length
  33458. var min = (l1 < l2) ? l1 : l2; // current path stop index
  33459. var shft = idx[1] - idx[0]; // shift
  33460. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  33461. while (pi <= min && p < path1nb) {
  33462. // 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
  33463. indices.push(pi, pi + shft, pi + 1);
  33464. indices.push(pi + shft + 1, pi + 1, pi + shft);
  33465. pi += 1;
  33466. if (pi === min) {
  33467. p++;
  33468. if (p === lg.length - 1) {
  33469. shft = idx[0] - idx[p];
  33470. l1 = lg[p] - 1;
  33471. l2 = lg[0] - 1;
  33472. }
  33473. else {
  33474. shft = idx[p + 1] - idx[p];
  33475. l1 = lg[p] - 1;
  33476. l2 = lg[p + 1] - 1;
  33477. }
  33478. pi = idx[p];
  33479. min = (l1 < l2) ? l1 + pi : l2 + pi;
  33480. }
  33481. }
  33482. // normals
  33483. VertexData.ComputeNormals(positions, indices, normals);
  33484. if (closePath) {
  33485. var indexFirst = 0;
  33486. var indexLast = 0;
  33487. for (p = 0; p < pathArray.length; p++) {
  33488. indexFirst = idx[p] * 3;
  33489. if (p + 1 < pathArray.length) {
  33490. indexLast = (idx[p + 1] - 1) * 3;
  33491. }
  33492. else {
  33493. indexLast = normals.length - 3;
  33494. }
  33495. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  33496. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  33497. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  33498. normals[indexLast] = normals[indexFirst];
  33499. normals[indexLast + 1] = normals[indexFirst + 1];
  33500. normals[indexLast + 2] = normals[indexFirst + 2];
  33501. }
  33502. }
  33503. // sides
  33504. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33505. // Colors
  33506. var colors = null;
  33507. if (customColors) {
  33508. colors = new Float32Array(customColors.length * 4);
  33509. for (var c = 0; c < customColors.length; c++) {
  33510. colors[c * 4] = customColors[c].r;
  33511. colors[c * 4 + 1] = customColors[c].g;
  33512. colors[c * 4 + 2] = customColors[c].b;
  33513. colors[c * 4 + 3] = customColors[c].a;
  33514. }
  33515. }
  33516. // Result
  33517. var vertexData = new VertexData();
  33518. var positions32 = new Float32Array(positions);
  33519. var normals32 = new Float32Array(normals);
  33520. var uvs32 = new Float32Array(uvs);
  33521. vertexData.indices = indices;
  33522. vertexData.positions = positions32;
  33523. vertexData.normals = normals32;
  33524. vertexData.uvs = uvs32;
  33525. if (colors) {
  33526. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  33527. }
  33528. if (closePath) {
  33529. vertexData._idx = idx;
  33530. }
  33531. return vertexData;
  33532. };
  33533. /**
  33534. * Creates the VertexData of the Box.
  33535. */
  33536. VertexData.CreateBox = function (options) {
  33537. var normalsSource = [
  33538. new BABYLON.Vector3(0, 0, 1),
  33539. new BABYLON.Vector3(0, 0, -1),
  33540. new BABYLON.Vector3(1, 0, 0),
  33541. new BABYLON.Vector3(-1, 0, 0),
  33542. new BABYLON.Vector3(0, 1, 0),
  33543. new BABYLON.Vector3(0, -1, 0)
  33544. ];
  33545. var indices = [];
  33546. var positions = [];
  33547. var normals = [];
  33548. var uvs = [];
  33549. var width = options.width || options.size || 1;
  33550. var height = options.height || options.size || 1;
  33551. var depth = options.depth || options.size || 1;
  33552. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33553. var faceUV = options.faceUV || new Array(6);
  33554. var faceColors = options.faceColors;
  33555. var colors = [];
  33556. // default face colors and UV if undefined
  33557. for (var f = 0; f < 6; f++) {
  33558. if (faceUV[f] === undefined) {
  33559. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33560. }
  33561. if (faceColors && faceColors[f] === undefined) {
  33562. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33563. }
  33564. }
  33565. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  33566. // Create each face in turn.
  33567. for (var index = 0; index < normalsSource.length; index++) {
  33568. var normal = normalsSource[index];
  33569. // Get two vectors perpendicular to the face normal and to each other.
  33570. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  33571. var side2 = BABYLON.Vector3.Cross(normal, side1);
  33572. // Six indices (two triangles) per face.
  33573. var verticesLength = positions.length / 3;
  33574. indices.push(verticesLength);
  33575. indices.push(verticesLength + 1);
  33576. indices.push(verticesLength + 2);
  33577. indices.push(verticesLength);
  33578. indices.push(verticesLength + 2);
  33579. indices.push(verticesLength + 3);
  33580. // Four vertices per face.
  33581. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  33582. positions.push(vertex.x, vertex.y, vertex.z);
  33583. normals.push(normal.x, normal.y, normal.z);
  33584. uvs.push(faceUV[index].z, faceUV[index].w);
  33585. if (faceColors) {
  33586. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33587. }
  33588. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  33589. positions.push(vertex.x, vertex.y, vertex.z);
  33590. normals.push(normal.x, normal.y, normal.z);
  33591. uvs.push(faceUV[index].x, faceUV[index].w);
  33592. if (faceColors) {
  33593. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33594. }
  33595. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  33596. positions.push(vertex.x, vertex.y, vertex.z);
  33597. normals.push(normal.x, normal.y, normal.z);
  33598. uvs.push(faceUV[index].x, faceUV[index].y);
  33599. if (faceColors) {
  33600. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33601. }
  33602. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  33603. positions.push(vertex.x, vertex.y, vertex.z);
  33604. normals.push(normal.x, normal.y, normal.z);
  33605. uvs.push(faceUV[index].z, faceUV[index].y);
  33606. if (faceColors) {
  33607. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33608. }
  33609. }
  33610. // sides
  33611. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33612. // Result
  33613. var vertexData = new VertexData();
  33614. vertexData.indices = indices;
  33615. vertexData.positions = positions;
  33616. vertexData.normals = normals;
  33617. vertexData.uvs = uvs;
  33618. if (faceColors) {
  33619. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33620. vertexData.colors = totalColors;
  33621. }
  33622. return vertexData;
  33623. };
  33624. /**
  33625. * Creates the VertexData of the Sphere.
  33626. */
  33627. VertexData.CreateSphere = function (options) {
  33628. var segments = options.segments || 32;
  33629. var diameterX = options.diameterX || options.diameter || 1;
  33630. var diameterY = options.diameterY || options.diameter || 1;
  33631. var diameterZ = options.diameterZ || options.diameter || 1;
  33632. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33633. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  33634. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33635. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  33636. var totalZRotationSteps = 2 + segments;
  33637. var totalYRotationSteps = 2 * totalZRotationSteps;
  33638. var indices = [];
  33639. var positions = [];
  33640. var normals = [];
  33641. var uvs = [];
  33642. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  33643. var normalizedZ = zRotationStep / totalZRotationSteps;
  33644. var angleZ = normalizedZ * Math.PI * slice;
  33645. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  33646. var normalizedY = yRotationStep / totalYRotationSteps;
  33647. var angleY = normalizedY * Math.PI * 2 * arc;
  33648. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  33649. var rotationY = BABYLON.Matrix.RotationY(angleY);
  33650. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  33651. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  33652. var vertex = complete.multiply(radius);
  33653. var normal = complete.divide(radius).normalize();
  33654. positions.push(vertex.x, vertex.y, vertex.z);
  33655. normals.push(normal.x, normal.y, normal.z);
  33656. uvs.push(normalizedY, normalizedZ);
  33657. }
  33658. if (zRotationStep > 0) {
  33659. var verticesCount = positions.length / 3;
  33660. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  33661. indices.push((firstIndex));
  33662. indices.push((firstIndex + 1));
  33663. indices.push(firstIndex + totalYRotationSteps + 1);
  33664. indices.push((firstIndex + totalYRotationSteps + 1));
  33665. indices.push((firstIndex + 1));
  33666. indices.push((firstIndex + totalYRotationSteps + 2));
  33667. }
  33668. }
  33669. }
  33670. // Sides
  33671. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33672. // Result
  33673. var vertexData = new VertexData();
  33674. vertexData.indices = indices;
  33675. vertexData.positions = positions;
  33676. vertexData.normals = normals;
  33677. vertexData.uvs = uvs;
  33678. return vertexData;
  33679. };
  33680. /**
  33681. * Creates the VertexData of the Cylinder or Cone.
  33682. */
  33683. VertexData.CreateCylinder = function (options) {
  33684. var height = options.height || 2;
  33685. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  33686. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  33687. var tessellation = options.tessellation || 24;
  33688. var subdivisions = options.subdivisions || 1;
  33689. var hasRings = options.hasRings ? true : false;
  33690. var enclose = options.enclose ? true : false;
  33691. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33692. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33693. var faceUV = options.faceUV || new Array(3);
  33694. var faceColors = options.faceColors;
  33695. // default face colors and UV if undefined
  33696. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  33697. var ringNb = (hasRings) ? subdivisions : 1;
  33698. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  33699. var f;
  33700. for (f = 0; f < surfaceNb; f++) {
  33701. if (faceColors && faceColors[f] === undefined) {
  33702. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33703. }
  33704. }
  33705. for (f = 0; f < surfaceNb; f++) {
  33706. if (faceUV && faceUV[f] === undefined) {
  33707. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33708. }
  33709. }
  33710. var indices = new Array();
  33711. var positions = new Array();
  33712. var normals = new Array();
  33713. var uvs = new Array();
  33714. var colors = new Array();
  33715. var angle_step = Math.PI * 2 * arc / tessellation;
  33716. var angle;
  33717. var h;
  33718. var radius;
  33719. var tan = (diameterBottom - diameterTop) / 2 / height;
  33720. var ringVertex = BABYLON.Vector3.Zero();
  33721. var ringNormal = BABYLON.Vector3.Zero();
  33722. var ringFirstVertex = BABYLON.Vector3.Zero();
  33723. var ringFirstNormal = BABYLON.Vector3.Zero();
  33724. var quadNormal = BABYLON.Vector3.Zero();
  33725. var Y = BABYLON.Axis.Y;
  33726. // positions, normals, uvs
  33727. var i;
  33728. var j;
  33729. var r;
  33730. var ringIdx = 1;
  33731. var s = 1; // surface index
  33732. var cs = 0;
  33733. var v = 0;
  33734. for (i = 0; i <= subdivisions; i++) {
  33735. h = i / subdivisions;
  33736. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  33737. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  33738. for (r = 0; r < ringIdx; r++) {
  33739. if (hasRings) {
  33740. s += r;
  33741. }
  33742. if (enclose) {
  33743. s += 2 * r;
  33744. }
  33745. for (j = 0; j <= tessellation; j++) {
  33746. angle = j * angle_step;
  33747. // position
  33748. ringVertex.x = Math.cos(-angle) * radius;
  33749. ringVertex.y = -height / 2 + h * height;
  33750. ringVertex.z = Math.sin(-angle) * radius;
  33751. // normal
  33752. if (diameterTop === 0 && i === subdivisions) {
  33753. // if no top cap, reuse former normals
  33754. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  33755. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  33756. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  33757. }
  33758. else {
  33759. ringNormal.x = ringVertex.x;
  33760. ringNormal.z = ringVertex.z;
  33761. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  33762. ringNormal.normalize();
  33763. }
  33764. // keep first ring vertex values for enclose
  33765. if (j === 0) {
  33766. ringFirstVertex.copyFrom(ringVertex);
  33767. ringFirstNormal.copyFrom(ringNormal);
  33768. }
  33769. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33770. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  33771. if (hasRings) {
  33772. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  33773. }
  33774. else {
  33775. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  33776. }
  33777. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  33778. if (faceColors) {
  33779. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  33780. }
  33781. }
  33782. // if enclose, add four vertices and their dedicated normals
  33783. if (arc !== 1 && enclose) {
  33784. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33785. positions.push(0, ringVertex.y, 0);
  33786. positions.push(0, ringVertex.y, 0);
  33787. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  33788. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  33789. quadNormal.normalize();
  33790. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33791. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  33792. quadNormal.normalize();
  33793. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33794. if (hasRings) {
  33795. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  33796. }
  33797. else {
  33798. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  33799. }
  33800. uvs.push(faceUV[s + 1].x, v);
  33801. uvs.push(faceUV[s + 1].z, v);
  33802. if (hasRings) {
  33803. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  33804. }
  33805. else {
  33806. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  33807. }
  33808. uvs.push(faceUV[s + 2].x, v);
  33809. uvs.push(faceUV[s + 2].z, v);
  33810. if (faceColors) {
  33811. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33812. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33813. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33814. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33815. }
  33816. }
  33817. if (cs !== s) {
  33818. cs = s;
  33819. }
  33820. }
  33821. }
  33822. // indices
  33823. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  33824. var s;
  33825. i = 0;
  33826. for (s = 0; s < subdivisions; s++) {
  33827. var i0 = 0;
  33828. var i1 = 0;
  33829. var i2 = 0;
  33830. var i3 = 0;
  33831. for (j = 0; j < tessellation; j++) {
  33832. i0 = i * (e + 1) + j;
  33833. i1 = (i + 1) * (e + 1) + j;
  33834. i2 = i * (e + 1) + (j + 1);
  33835. i3 = (i + 1) * (e + 1) + (j + 1);
  33836. indices.push(i0, i1, i2);
  33837. indices.push(i3, i2, i1);
  33838. }
  33839. if (arc !== 1 && enclose) {
  33840. indices.push(i0 + 2, i1 + 2, i2 + 2);
  33841. indices.push(i3 + 2, i2 + 2, i1 + 2);
  33842. indices.push(i0 + 4, i1 + 4, i2 + 4);
  33843. indices.push(i3 + 4, i2 + 4, i1 + 4);
  33844. }
  33845. i = (hasRings) ? (i + 2) : (i + 1);
  33846. }
  33847. // Caps
  33848. var createCylinderCap = function (isTop) {
  33849. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  33850. if (radius === 0) {
  33851. return;
  33852. }
  33853. // Cap positions, normals & uvs
  33854. var angle;
  33855. var circleVector;
  33856. var i;
  33857. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  33858. var c = null;
  33859. if (faceColors) {
  33860. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  33861. }
  33862. // cap center
  33863. var vbase = positions.length / 3;
  33864. var offset = isTop ? height / 2 : -height / 2;
  33865. var center = new BABYLON.Vector3(0, offset, 0);
  33866. positions.push(center.x, center.y, center.z);
  33867. normals.push(0, isTop ? 1 : -1, 0);
  33868. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  33869. if (c) {
  33870. colors.push(c.r, c.g, c.b, c.a);
  33871. }
  33872. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  33873. for (i = 0; i <= tessellation; i++) {
  33874. angle = Math.PI * 2 * i * arc / tessellation;
  33875. var cos = Math.cos(-angle);
  33876. var sin = Math.sin(-angle);
  33877. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  33878. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  33879. positions.push(circleVector.x, circleVector.y, circleVector.z);
  33880. normals.push(0, isTop ? 1 : -1, 0);
  33881. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  33882. if (c) {
  33883. colors.push(c.r, c.g, c.b, c.a);
  33884. }
  33885. }
  33886. // Cap indices
  33887. for (i = 0; i < tessellation; i++) {
  33888. if (!isTop) {
  33889. indices.push(vbase);
  33890. indices.push(vbase + (i + 1));
  33891. indices.push(vbase + (i + 2));
  33892. }
  33893. else {
  33894. indices.push(vbase);
  33895. indices.push(vbase + (i + 2));
  33896. indices.push(vbase + (i + 1));
  33897. }
  33898. }
  33899. };
  33900. // add caps to geometry
  33901. createCylinderCap(false);
  33902. createCylinderCap(true);
  33903. // Sides
  33904. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33905. var vertexData = new VertexData();
  33906. vertexData.indices = indices;
  33907. vertexData.positions = positions;
  33908. vertexData.normals = normals;
  33909. vertexData.uvs = uvs;
  33910. if (faceColors) {
  33911. vertexData.colors = colors;
  33912. }
  33913. return vertexData;
  33914. };
  33915. /**
  33916. * Creates the VertexData of the Torus.
  33917. */
  33918. VertexData.CreateTorus = function (options) {
  33919. var indices = [];
  33920. var positions = [];
  33921. var normals = [];
  33922. var uvs = [];
  33923. var diameter = options.diameter || 1;
  33924. var thickness = options.thickness || 0.5;
  33925. var tessellation = options.tessellation || 16;
  33926. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33927. var stride = tessellation + 1;
  33928. for (var i = 0; i <= tessellation; i++) {
  33929. var u = i / tessellation;
  33930. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  33931. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  33932. for (var j = 0; j <= tessellation; j++) {
  33933. var v = 1 - j / tessellation;
  33934. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  33935. var dx = Math.cos(innerAngle);
  33936. var dy = Math.sin(innerAngle);
  33937. // Create a vertex.
  33938. var normal = new BABYLON.Vector3(dx, dy, 0);
  33939. var position = normal.scale(thickness / 2);
  33940. var textureCoordinate = new BABYLON.Vector2(u, v);
  33941. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  33942. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  33943. positions.push(position.x, position.y, position.z);
  33944. normals.push(normal.x, normal.y, normal.z);
  33945. uvs.push(textureCoordinate.x, textureCoordinate.y);
  33946. // And create indices for two triangles.
  33947. var nextI = (i + 1) % stride;
  33948. var nextJ = (j + 1) % stride;
  33949. indices.push(i * stride + j);
  33950. indices.push(i * stride + nextJ);
  33951. indices.push(nextI * stride + j);
  33952. indices.push(i * stride + nextJ);
  33953. indices.push(nextI * stride + nextJ);
  33954. indices.push(nextI * stride + j);
  33955. }
  33956. }
  33957. // Sides
  33958. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  33959. // Result
  33960. var vertexData = new VertexData();
  33961. vertexData.indices = indices;
  33962. vertexData.positions = positions;
  33963. vertexData.normals = normals;
  33964. vertexData.uvs = uvs;
  33965. return vertexData;
  33966. };
  33967. /**
  33968. * Creates the VertexData of the LineSystem.
  33969. */
  33970. VertexData.CreateLineSystem = function (options) {
  33971. var indices = [];
  33972. var positions = [];
  33973. var lines = options.lines;
  33974. var colors = options.colors;
  33975. var vertexColors = [];
  33976. var idx = 0;
  33977. for (var l = 0; l < lines.length; l++) {
  33978. var points = lines[l];
  33979. for (var index = 0; index < points.length; index++) {
  33980. positions.push(points[index].x, points[index].y, points[index].z);
  33981. if (colors) {
  33982. var color = colors[l];
  33983. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  33984. }
  33985. if (index > 0) {
  33986. indices.push(idx - 1);
  33987. indices.push(idx);
  33988. }
  33989. idx++;
  33990. }
  33991. }
  33992. var vertexData = new VertexData();
  33993. vertexData.indices = indices;
  33994. vertexData.positions = positions;
  33995. if (colors) {
  33996. vertexData.colors = vertexColors;
  33997. }
  33998. return vertexData;
  33999. };
  34000. /**
  34001. * Create the VertexData of the DashedLines.
  34002. */
  34003. VertexData.CreateDashedLines = function (options) {
  34004. var dashSize = options.dashSize || 3;
  34005. var gapSize = options.gapSize || 1;
  34006. var dashNb = options.dashNb || 200;
  34007. var points = options.points;
  34008. var positions = new Array();
  34009. var indices = new Array();
  34010. var curvect = BABYLON.Vector3.Zero();
  34011. var lg = 0;
  34012. var nb = 0;
  34013. var shft = 0;
  34014. var dashshft = 0;
  34015. var curshft = 0;
  34016. var idx = 0;
  34017. var i = 0;
  34018. for (i = 0; i < points.length - 1; i++) {
  34019. points[i + 1].subtractToRef(points[i], curvect);
  34020. lg += curvect.length();
  34021. }
  34022. shft = lg / dashNb;
  34023. dashshft = dashSize * shft / (dashSize + gapSize);
  34024. for (i = 0; i < points.length - 1; i++) {
  34025. points[i + 1].subtractToRef(points[i], curvect);
  34026. nb = Math.floor(curvect.length() / shft);
  34027. curvect.normalize();
  34028. for (var j = 0; j < nb; j++) {
  34029. curshft = shft * j;
  34030. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  34031. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  34032. indices.push(idx, idx + 1);
  34033. idx += 2;
  34034. }
  34035. }
  34036. // Result
  34037. var vertexData = new VertexData();
  34038. vertexData.positions = positions;
  34039. vertexData.indices = indices;
  34040. return vertexData;
  34041. };
  34042. /**
  34043. * Creates the VertexData of the Ground.
  34044. */
  34045. VertexData.CreateGround = function (options) {
  34046. var indices = [];
  34047. var positions = [];
  34048. var normals = [];
  34049. var uvs = [];
  34050. var row, col;
  34051. var width = options.width || 1;
  34052. var height = options.height || 1;
  34053. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  34054. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  34055. for (row = 0; row <= subdivisionsY; row++) {
  34056. for (col = 0; col <= subdivisionsX; col++) {
  34057. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  34058. var normal = new BABYLON.Vector3(0, 1.0, 0);
  34059. positions.push(position.x, position.y, position.z);
  34060. normals.push(normal.x, normal.y, normal.z);
  34061. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  34062. }
  34063. }
  34064. for (row = 0; row < subdivisionsY; row++) {
  34065. for (col = 0; col < subdivisionsX; col++) {
  34066. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  34067. indices.push(col + 1 + row * (subdivisionsX + 1));
  34068. indices.push(col + row * (subdivisionsX + 1));
  34069. indices.push(col + (row + 1) * (subdivisionsX + 1));
  34070. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  34071. indices.push(col + row * (subdivisionsX + 1));
  34072. }
  34073. }
  34074. // Result
  34075. var vertexData = new VertexData();
  34076. vertexData.indices = indices;
  34077. vertexData.positions = positions;
  34078. vertexData.normals = normals;
  34079. vertexData.uvs = uvs;
  34080. return vertexData;
  34081. };
  34082. /**
  34083. * Creates the VertexData of the TiledGround.
  34084. */
  34085. VertexData.CreateTiledGround = function (options) {
  34086. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  34087. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  34088. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  34089. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  34090. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  34091. var precision = options.precision || { w: 1, h: 1 };
  34092. var indices = new Array();
  34093. var positions = new Array();
  34094. var normals = new Array();
  34095. var uvs = new Array();
  34096. var row, col, tileRow, tileCol;
  34097. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  34098. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  34099. precision.w = (precision.w < 1) ? 1 : precision.w;
  34100. precision.h = (precision.h < 1) ? 1 : precision.h;
  34101. var tileSize = {
  34102. 'w': (xmax - xmin) / subdivisions.w,
  34103. 'h': (zmax - zmin) / subdivisions.h
  34104. };
  34105. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  34106. // Indices
  34107. var base = positions.length / 3;
  34108. var rowLength = precision.w + 1;
  34109. for (row = 0; row < precision.h; row++) {
  34110. for (col = 0; col < precision.w; col++) {
  34111. var square = [
  34112. base + col + row * rowLength,
  34113. base + (col + 1) + row * rowLength,
  34114. base + (col + 1) + (row + 1) * rowLength,
  34115. base + col + (row + 1) * rowLength
  34116. ];
  34117. indices.push(square[1]);
  34118. indices.push(square[2]);
  34119. indices.push(square[3]);
  34120. indices.push(square[0]);
  34121. indices.push(square[1]);
  34122. indices.push(square[3]);
  34123. }
  34124. }
  34125. // Position, normals and uvs
  34126. var position = BABYLON.Vector3.Zero();
  34127. var normal = new BABYLON.Vector3(0, 1.0, 0);
  34128. for (row = 0; row <= precision.h; row++) {
  34129. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  34130. for (col = 0; col <= precision.w; col++) {
  34131. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  34132. position.y = 0;
  34133. positions.push(position.x, position.y, position.z);
  34134. normals.push(normal.x, normal.y, normal.z);
  34135. uvs.push(col / precision.w, row / precision.h);
  34136. }
  34137. }
  34138. }
  34139. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  34140. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  34141. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  34142. }
  34143. }
  34144. // Result
  34145. var vertexData = new VertexData();
  34146. vertexData.indices = indices;
  34147. vertexData.positions = positions;
  34148. vertexData.normals = normals;
  34149. vertexData.uvs = uvs;
  34150. return vertexData;
  34151. };
  34152. /**
  34153. * Creates the VertexData of the Ground designed from a heightmap.
  34154. */
  34155. VertexData.CreateGroundFromHeightMap = function (options) {
  34156. var indices = [];
  34157. var positions = [];
  34158. var normals = [];
  34159. var uvs = [];
  34160. var row, col;
  34161. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  34162. // Vertices
  34163. for (row = 0; row <= options.subdivisions; row++) {
  34164. for (col = 0; col <= options.subdivisions; col++) {
  34165. 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));
  34166. // Compute height
  34167. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  34168. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  34169. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  34170. var r = options.buffer[pos] / 255.0;
  34171. var g = options.buffer[pos + 1] / 255.0;
  34172. var b = options.buffer[pos + 2] / 255.0;
  34173. var gradient = r * filter.r + g * filter.g + b * filter.b;
  34174. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  34175. // Add vertex
  34176. positions.push(position.x, position.y, position.z);
  34177. normals.push(0, 0, 0);
  34178. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  34179. }
  34180. }
  34181. // Indices
  34182. for (row = 0; row < options.subdivisions; row++) {
  34183. for (col = 0; col < options.subdivisions; col++) {
  34184. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  34185. indices.push(col + 1 + row * (options.subdivisions + 1));
  34186. indices.push(col + row * (options.subdivisions + 1));
  34187. indices.push(col + (row + 1) * (options.subdivisions + 1));
  34188. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  34189. indices.push(col + row * (options.subdivisions + 1));
  34190. }
  34191. }
  34192. // Normals
  34193. VertexData.ComputeNormals(positions, indices, normals);
  34194. // Result
  34195. var vertexData = new VertexData();
  34196. vertexData.indices = indices;
  34197. vertexData.positions = positions;
  34198. vertexData.normals = normals;
  34199. vertexData.uvs = uvs;
  34200. return vertexData;
  34201. };
  34202. /**
  34203. * Creates the VertexData of the Plane.
  34204. */
  34205. VertexData.CreatePlane = function (options) {
  34206. var indices = [];
  34207. var positions = [];
  34208. var normals = [];
  34209. var uvs = [];
  34210. var width = options.width || options.size || 1;
  34211. var height = options.height || options.size || 1;
  34212. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34213. // Vertices
  34214. var halfWidth = width / 2.0;
  34215. var halfHeight = height / 2.0;
  34216. positions.push(-halfWidth, -halfHeight, 0);
  34217. normals.push(0, 0, -1.0);
  34218. uvs.push(0.0, 0.0);
  34219. positions.push(halfWidth, -halfHeight, 0);
  34220. normals.push(0, 0, -1.0);
  34221. uvs.push(1.0, 0.0);
  34222. positions.push(halfWidth, halfHeight, 0);
  34223. normals.push(0, 0, -1.0);
  34224. uvs.push(1.0, 1.0);
  34225. positions.push(-halfWidth, halfHeight, 0);
  34226. normals.push(0, 0, -1.0);
  34227. uvs.push(0.0, 1.0);
  34228. // Indices
  34229. indices.push(0);
  34230. indices.push(1);
  34231. indices.push(2);
  34232. indices.push(0);
  34233. indices.push(2);
  34234. indices.push(3);
  34235. // Sides
  34236. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34237. // Result
  34238. var vertexData = new VertexData();
  34239. vertexData.indices = indices;
  34240. vertexData.positions = positions;
  34241. vertexData.normals = normals;
  34242. vertexData.uvs = uvs;
  34243. return vertexData;
  34244. };
  34245. /**
  34246. * Creates the VertexData of the Disc or regular Polygon.
  34247. */
  34248. VertexData.CreateDisc = function (options) {
  34249. var positions = new Array();
  34250. var indices = new Array();
  34251. var normals = new Array();
  34252. var uvs = new Array();
  34253. var radius = options.radius || 0.5;
  34254. var tessellation = options.tessellation || 64;
  34255. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  34256. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34257. // positions and uvs
  34258. positions.push(0, 0, 0); // disc center first
  34259. uvs.push(0.5, 0.5);
  34260. var theta = Math.PI * 2 * arc;
  34261. var step = theta / tessellation;
  34262. for (var a = 0; a < theta; a += step) {
  34263. var x = Math.cos(a);
  34264. var y = Math.sin(a);
  34265. var u = (x + 1) / 2;
  34266. var v = (1 - y) / 2;
  34267. positions.push(radius * x, radius * y, 0);
  34268. uvs.push(u, v);
  34269. }
  34270. if (arc === 1) {
  34271. positions.push(positions[3], positions[4], positions[5]); // close the circle
  34272. uvs.push(uvs[2], uvs[3]);
  34273. }
  34274. //indices
  34275. var vertexNb = positions.length / 3;
  34276. for (var i = 1; i < vertexNb - 1; i++) {
  34277. indices.push(i + 1, 0, i);
  34278. }
  34279. // result
  34280. VertexData.ComputeNormals(positions, indices, normals);
  34281. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34282. var vertexData = new VertexData();
  34283. vertexData.indices = indices;
  34284. vertexData.positions = positions;
  34285. vertexData.normals = normals;
  34286. vertexData.uvs = uvs;
  34287. return vertexData;
  34288. };
  34289. /**
  34290. * Re-creates the VertexData of the Polygon for sideOrientation.
  34291. */
  34292. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  34293. var faceUV = fUV || new Array(3);
  34294. var faceColors = fColors;
  34295. var colors = [];
  34296. // default face colors and UV if undefined
  34297. for (var f = 0; f < 3; f++) {
  34298. if (faceUV[f] === undefined) {
  34299. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34300. }
  34301. if (faceColors && faceColors[f] === undefined) {
  34302. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34303. }
  34304. }
  34305. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34306. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34307. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  34308. var indices = polygon.getIndices();
  34309. // set face colours and textures
  34310. var idx = 0;
  34311. var face = 0;
  34312. for (var index = 0; index < normals.length; index += 3) {
  34313. //Edge Face no. 1
  34314. if (Math.abs(normals[index + 1]) < 0.001) {
  34315. face = 1;
  34316. }
  34317. //Top Face no. 0
  34318. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  34319. face = 0;
  34320. }
  34321. //Bottom Face no. 2
  34322. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  34323. face = 2;
  34324. }
  34325. idx = index / 3;
  34326. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  34327. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  34328. if (faceColors) {
  34329. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  34330. }
  34331. }
  34332. // sides
  34333. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  34334. // Result
  34335. var vertexData = new VertexData();
  34336. vertexData.indices = indices;
  34337. vertexData.positions = positions;
  34338. vertexData.normals = normals;
  34339. vertexData.uvs = uvs;
  34340. if (faceColors) {
  34341. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  34342. vertexData.colors = totalColors;
  34343. }
  34344. return vertexData;
  34345. };
  34346. /**
  34347. * Creates the VertexData of the IcoSphere.
  34348. */
  34349. VertexData.CreateIcoSphere = function (options) {
  34350. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34351. var radius = options.radius || 1;
  34352. var flat = (options.flat === undefined) ? true : options.flat;
  34353. var subdivisions = options.subdivisions || 4;
  34354. var radiusX = options.radiusX || radius;
  34355. var radiusY = options.radiusY || radius;
  34356. var radiusZ = options.radiusZ || radius;
  34357. var t = (1 + Math.sqrt(5)) / 2;
  34358. // 12 vertex x,y,z
  34359. var ico_vertices = [
  34360. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  34361. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  34362. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  34363. ];
  34364. // index of 3 vertex makes a face of icopshere
  34365. var ico_indices = [
  34366. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  34367. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  34368. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  34369. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  34370. ];
  34371. // vertex for uv have aliased position, not for UV
  34372. var vertices_unalias_id = [
  34373. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  34374. // vertex alias
  34375. 0,
  34376. 2,
  34377. 3,
  34378. 3,
  34379. 3,
  34380. 4,
  34381. 7,
  34382. 8,
  34383. 9,
  34384. 9,
  34385. 10,
  34386. 11 // 23: B + 12
  34387. ];
  34388. // uv as integer step (not pixels !)
  34389. var ico_vertexuv = [
  34390. 5, 1, 3, 1, 6, 4, 0, 0,
  34391. 5, 3, 4, 2, 2, 2, 4, 0,
  34392. 2, 0, 1, 1, 6, 0, 6, 2,
  34393. // vertex alias (for same vertex on different faces)
  34394. 0, 4,
  34395. 3, 3,
  34396. 4, 4,
  34397. 3, 1,
  34398. 4, 2,
  34399. 4, 4,
  34400. 0, 2,
  34401. 1, 1,
  34402. 2, 2,
  34403. 3, 3,
  34404. 1, 3,
  34405. 2, 4 // 23: B + 12
  34406. ];
  34407. // Vertices[0, 1, ...9, A, B] : position on UV plane
  34408. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  34409. // First island of uv mapping
  34410. // v = 4h 3+ 2
  34411. // v = 3h 9+ 4
  34412. // v = 2h 9+ 5 B
  34413. // v = 1h 9 1 0
  34414. // v = 0h 3 8 7 A
  34415. // u = 0 1 2 3 4 5 6 *a
  34416. // Second island of uv mapping
  34417. // v = 4h 0+ B+ 4+
  34418. // v = 3h A+ 2+
  34419. // v = 2h 7+ 6 3+
  34420. // v = 1h 8+ 3+
  34421. // v = 0h
  34422. // u = 0 1 2 3 4 5 6 *a
  34423. // Face layout on texture UV mapping
  34424. // ============
  34425. // \ 4 /\ 16 / ======
  34426. // \ / \ / /\ 11 /
  34427. // \/ 7 \/ / \ /
  34428. // ======= / 10 \/
  34429. // /\ 17 /\ =======
  34430. // / \ / \ \ 15 /\
  34431. // / 8 \/ 12 \ \ / \
  34432. // ============ \/ 6 \
  34433. // \ 18 /\ ============
  34434. // \ / \ \ 5 /\ 0 /
  34435. // \/ 13 \ \ / \ /
  34436. // ======= \/ 1 \/
  34437. // =============
  34438. // /\ 19 /\ 2 /\
  34439. // / \ / \ / \
  34440. // / 14 \/ 9 \/ 3 \
  34441. // ===================
  34442. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  34443. var ustep = 138 / 1024;
  34444. var vstep = 239 / 1024;
  34445. var uoffset = 60 / 1024;
  34446. var voffset = 26 / 1024;
  34447. // Second island should have margin, not to touch the first island
  34448. // avoid any borderline artefact in pixel rounding
  34449. var island_u_offset = -40 / 1024;
  34450. var island_v_offset = +20 / 1024;
  34451. // face is either island 0 or 1 :
  34452. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  34453. var island = [
  34454. 0, 0, 0, 0, 1,
  34455. 0, 0, 1, 1, 0,
  34456. 0, 0, 1, 1, 0,
  34457. 0, 1, 1, 1, 0 // 15 - 19
  34458. ];
  34459. var indices = new Array();
  34460. var positions = new Array();
  34461. var normals = new Array();
  34462. var uvs = new Array();
  34463. var current_indice = 0;
  34464. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  34465. var face_vertex_pos = new Array(3);
  34466. var face_vertex_uv = new Array(3);
  34467. var v012;
  34468. for (v012 = 0; v012 < 3; v012++) {
  34469. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  34470. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  34471. }
  34472. // create all with normals
  34473. for (var face = 0; face < 20; face++) {
  34474. // 3 vertex per face
  34475. for (v012 = 0; v012 < 3; v012++) {
  34476. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  34477. var v_id = ico_indices[3 * face + v012];
  34478. // vertex have 3D position (x,y,z)
  34479. 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]);
  34480. // Normalize to get normal, then scale to radius
  34481. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  34482. // uv Coordinates from vertex ID
  34483. 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);
  34484. }
  34485. // Subdivide the face (interpolate pos, norm, uv)
  34486. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  34487. // - norm is linear interpolation of vertex corner normal
  34488. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  34489. // - uv is linear interpolation
  34490. //
  34491. // Topology is as below for sub-divide by 2
  34492. // vertex shown as v0,v1,v2
  34493. // interp index is i1 to progress in range [v0,v1[
  34494. // interp index is i2 to progress in range [v0,v2[
  34495. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  34496. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34497. //
  34498. //
  34499. // i2 v2
  34500. // ^ ^
  34501. // / / \
  34502. // / / \
  34503. // / / \
  34504. // / / (0,1) \
  34505. // / #---------\
  34506. // / / \ (0,0)'/ \
  34507. // / / \ / \
  34508. // / / \ / \
  34509. // / / (0,0) \ / (1,0) \
  34510. // / #---------#---------\
  34511. // v0 v1
  34512. //
  34513. // --------------------> i1
  34514. //
  34515. // interp of (i1,i2):
  34516. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  34517. // along i1 : lerp(x0,x1, i1/(S-i2))
  34518. //
  34519. // centroid of triangle is needed to get help normal computation
  34520. // (c1,c2) are used for centroid location
  34521. var interp_vertex = function (i1, i2, c1, c2) {
  34522. // vertex is interpolated from
  34523. // - face_vertex_pos[0..2]
  34524. // - face_vertex_uv[0..2]
  34525. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  34526. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  34527. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  34528. pos_interp.normalize();
  34529. var vertex_normal;
  34530. if (flat) {
  34531. // in flat mode, recalculate normal as face centroid normal
  34532. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  34533. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  34534. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  34535. }
  34536. else {
  34537. // in smooth mode, recalculate normal from each single vertex position
  34538. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  34539. }
  34540. // Vertex normal need correction due to X,Y,Z radius scaling
  34541. vertex_normal.x /= radiusX;
  34542. vertex_normal.y /= radiusY;
  34543. vertex_normal.z /= radiusZ;
  34544. vertex_normal.normalize();
  34545. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  34546. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  34547. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  34548. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  34549. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  34550. uvs.push(uv_interp.x, uv_interp.y);
  34551. // push each vertex has member of a face
  34552. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  34553. indices.push(current_indice);
  34554. current_indice++;
  34555. };
  34556. for (var i2 = 0; i2 < subdivisions; i2++) {
  34557. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  34558. // face : (i1,i2) for /\ :
  34559. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  34560. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34561. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34562. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34563. if (i1 + i2 + 1 < subdivisions) {
  34564. // face : (i1,i2)' for \/ :
  34565. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34566. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34567. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34568. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34569. }
  34570. }
  34571. }
  34572. }
  34573. // Sides
  34574. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34575. // Result
  34576. var vertexData = new VertexData();
  34577. vertexData.indices = indices;
  34578. vertexData.positions = positions;
  34579. vertexData.normals = normals;
  34580. vertexData.uvs = uvs;
  34581. return vertexData;
  34582. };
  34583. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  34584. /**
  34585. * Creates the VertexData of the Polyhedron.
  34586. */
  34587. VertexData.CreatePolyhedron = function (options) {
  34588. // provided polyhedron types :
  34589. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  34590. // 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)
  34591. var polyhedra = [];
  34592. 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]] };
  34593. 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]] };
  34594. polyhedra[2] = {
  34595. 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]],
  34596. 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]]
  34597. };
  34598. polyhedra[3] = {
  34599. 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]],
  34600. 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]]
  34601. };
  34602. polyhedra[4] = {
  34603. 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]],
  34604. 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]]
  34605. };
  34606. 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]] };
  34607. 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]] };
  34608. 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]] };
  34609. 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]] };
  34610. 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]] };
  34611. 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]] };
  34612. 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]] };
  34613. 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]] };
  34614. 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]] };
  34615. polyhedra[14] = {
  34616. 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]],
  34617. 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]]
  34618. };
  34619. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  34620. var size = options.size;
  34621. var sizeX = options.sizeX || size || 1;
  34622. var sizeY = options.sizeY || size || 1;
  34623. var sizeZ = options.sizeZ || size || 1;
  34624. var data = options.custom || polyhedra[type];
  34625. var nbfaces = data.face.length;
  34626. var faceUV = options.faceUV || new Array(nbfaces);
  34627. var faceColors = options.faceColors;
  34628. var flat = (options.flat === undefined) ? true : options.flat;
  34629. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34630. var positions = new Array();
  34631. var indices = new Array();
  34632. var normals = new Array();
  34633. var uvs = new Array();
  34634. var colors = new Array();
  34635. var index = 0;
  34636. var faceIdx = 0; // face cursor in the array "indexes"
  34637. var indexes = new Array();
  34638. var i = 0;
  34639. var f = 0;
  34640. var u, v, ang, x, y, tmp;
  34641. // default face colors and UV if undefined
  34642. if (flat) {
  34643. for (f = 0; f < nbfaces; f++) {
  34644. if (faceColors && faceColors[f] === undefined) {
  34645. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34646. }
  34647. if (faceUV && faceUV[f] === undefined) {
  34648. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34649. }
  34650. }
  34651. }
  34652. if (!flat) {
  34653. for (i = 0; i < data.vertex.length; i++) {
  34654. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  34655. uvs.push(0, 0);
  34656. }
  34657. for (f = 0; f < nbfaces; f++) {
  34658. for (i = 0; i < data.face[f].length - 2; i++) {
  34659. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  34660. }
  34661. }
  34662. }
  34663. else {
  34664. for (f = 0; f < nbfaces; f++) {
  34665. var fl = data.face[f].length; // number of vertices of the current face
  34666. ang = 2 * Math.PI / fl;
  34667. x = 0.5 * Math.tan(ang / 2);
  34668. y = 0.5;
  34669. // positions, uvs, colors
  34670. for (i = 0; i < fl; i++) {
  34671. // positions
  34672. 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);
  34673. indexes.push(index);
  34674. index++;
  34675. // uvs
  34676. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  34677. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  34678. uvs.push(u, v);
  34679. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  34680. y = x * Math.sin(ang) + y * Math.cos(ang);
  34681. x = tmp;
  34682. // colors
  34683. if (faceColors) {
  34684. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  34685. }
  34686. }
  34687. // indices from indexes
  34688. for (i = 0; i < fl - 2; i++) {
  34689. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  34690. }
  34691. faceIdx += fl;
  34692. }
  34693. }
  34694. VertexData.ComputeNormals(positions, indices, normals);
  34695. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34696. var vertexData = new VertexData();
  34697. vertexData.positions = positions;
  34698. vertexData.indices = indices;
  34699. vertexData.normals = normals;
  34700. vertexData.uvs = uvs;
  34701. if (faceColors && flat) {
  34702. vertexData.colors = colors;
  34703. }
  34704. return vertexData;
  34705. };
  34706. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  34707. /**
  34708. * Creates the VertexData of the Torus Knot.
  34709. */
  34710. VertexData.CreateTorusKnot = function (options) {
  34711. var indices = new Array();
  34712. var positions = new Array();
  34713. var normals = new Array();
  34714. var uvs = new Array();
  34715. var radius = options.radius || 2;
  34716. var tube = options.tube || 0.5;
  34717. var radialSegments = options.radialSegments || 32;
  34718. var tubularSegments = options.tubularSegments || 32;
  34719. var p = options.p || 2;
  34720. var q = options.q || 3;
  34721. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34722. // Helper
  34723. var getPos = function (angle) {
  34724. var cu = Math.cos(angle);
  34725. var su = Math.sin(angle);
  34726. var quOverP = q / p * angle;
  34727. var cs = Math.cos(quOverP);
  34728. var tx = radius * (2 + cs) * 0.5 * cu;
  34729. var ty = radius * (2 + cs) * su * 0.5;
  34730. var tz = radius * Math.sin(quOverP) * 0.5;
  34731. return new BABYLON.Vector3(tx, ty, tz);
  34732. };
  34733. // Vertices
  34734. var i;
  34735. var j;
  34736. for (i = 0; i <= radialSegments; i++) {
  34737. var modI = i % radialSegments;
  34738. var u = modI / radialSegments * 2 * p * Math.PI;
  34739. var p1 = getPos(u);
  34740. var p2 = getPos(u + 0.01);
  34741. var tang = p2.subtract(p1);
  34742. var n = p2.add(p1);
  34743. var bitan = BABYLON.Vector3.Cross(tang, n);
  34744. n = BABYLON.Vector3.Cross(bitan, tang);
  34745. bitan.normalize();
  34746. n.normalize();
  34747. for (j = 0; j < tubularSegments; j++) {
  34748. var modJ = j % tubularSegments;
  34749. var v = modJ / tubularSegments * 2 * Math.PI;
  34750. var cx = -tube * Math.cos(v);
  34751. var cy = tube * Math.sin(v);
  34752. positions.push(p1.x + cx * n.x + cy * bitan.x);
  34753. positions.push(p1.y + cx * n.y + cy * bitan.y);
  34754. positions.push(p1.z + cx * n.z + cy * bitan.z);
  34755. uvs.push(i / radialSegments);
  34756. uvs.push(j / tubularSegments);
  34757. }
  34758. }
  34759. for (i = 0; i < radialSegments; i++) {
  34760. for (j = 0; j < tubularSegments; j++) {
  34761. var jNext = (j + 1) % tubularSegments;
  34762. var a = i * tubularSegments + j;
  34763. var b = (i + 1) * tubularSegments + j;
  34764. var c = (i + 1) * tubularSegments + jNext;
  34765. var d = i * tubularSegments + jNext;
  34766. indices.push(d);
  34767. indices.push(b);
  34768. indices.push(a);
  34769. indices.push(d);
  34770. indices.push(c);
  34771. indices.push(b);
  34772. }
  34773. }
  34774. // Normals
  34775. VertexData.ComputeNormals(positions, indices, normals);
  34776. // Sides
  34777. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  34778. // Result
  34779. var vertexData = new VertexData();
  34780. vertexData.indices = indices;
  34781. vertexData.positions = positions;
  34782. vertexData.normals = normals;
  34783. vertexData.uvs = uvs;
  34784. return vertexData;
  34785. };
  34786. // Tools
  34787. /**
  34788. * @param {any} - positions (number[] or Float32Array)
  34789. * @param {any} - indices (number[] or Uint16Array)
  34790. * @param {any} - normals (number[] or Float32Array)
  34791. * options (optional) :
  34792. * facetPositions : optional array of facet positions (vector3)
  34793. * facetNormals : optional array of facet normals (vector3)
  34794. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  34795. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  34796. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  34797. * bbSize : optional bounding box size data, required for facetPartitioning computation
  34798. * bInfo : optional bounding info, required for facetPartitioning computation
  34799. * useRightHandedSystem: optional boolean to for right handed system computation
  34800. * depthSort : optional boolean to enable the facet depth sort computation
  34801. * distanceTo : optional Vector3 to compute the facet depth from this location
  34802. * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  34803. */
  34804. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  34805. // temporary scalar variables
  34806. var index = 0; // facet index
  34807. var p1p2x = 0.0; // p1p2 vector x coordinate
  34808. var p1p2y = 0.0; // p1p2 vector y coordinate
  34809. var p1p2z = 0.0; // p1p2 vector z coordinate
  34810. var p3p2x = 0.0; // p3p2 vector x coordinate
  34811. var p3p2y = 0.0; // p3p2 vector y coordinate
  34812. var p3p2z = 0.0; // p3p2 vector z coordinate
  34813. var faceNormalx = 0.0; // facet normal x coordinate
  34814. var faceNormaly = 0.0; // facet normal y coordinate
  34815. var faceNormalz = 0.0; // facet normal z coordinate
  34816. var length = 0.0; // facet normal length before normalization
  34817. var v1x = 0; // vector1 x index in the positions array
  34818. var v1y = 0; // vector1 y index in the positions array
  34819. var v1z = 0; // vector1 z index in the positions array
  34820. var v2x = 0; // vector2 x index in the positions array
  34821. var v2y = 0; // vector2 y index in the positions array
  34822. var v2z = 0; // vector2 z index in the positions array
  34823. var v3x = 0; // vector3 x index in the positions array
  34824. var v3y = 0; // vector3 y index in the positions array
  34825. var v3z = 0; // vector3 z index in the positions array
  34826. var computeFacetNormals = false;
  34827. var computeFacetPositions = false;
  34828. var computeFacetPartitioning = false;
  34829. var computeDepthSort = false;
  34830. var faceNormalSign = 1;
  34831. var ratio = 0;
  34832. var distanceTo = null;
  34833. if (options) {
  34834. computeFacetNormals = (options.facetNormals) ? true : false;
  34835. computeFacetPositions = (options.facetPositions) ? true : false;
  34836. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  34837. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  34838. ratio = options.ratio || 0;
  34839. computeDepthSort = (options.depthSort) ? true : false;
  34840. distanceTo = (options.distanceTo);
  34841. if (computeDepthSort) {
  34842. if (distanceTo === undefined) {
  34843. distanceTo = BABYLON.Vector3.Zero();
  34844. }
  34845. var depthSortedFacets = options.depthSortedFacets;
  34846. }
  34847. }
  34848. // facetPartitioning reinit if needed
  34849. var xSubRatio = 0;
  34850. var ySubRatio = 0;
  34851. var zSubRatio = 0;
  34852. var subSq = 0;
  34853. if (computeFacetPartitioning && options && options.bbSize) {
  34854. var ox = 0; // X partitioning index for facet position
  34855. var oy = 0; // Y partinioning index for facet position
  34856. var oz = 0; // Z partinioning index for facet position
  34857. var b1x = 0; // X partitioning index for facet v1 vertex
  34858. var b1y = 0; // Y partitioning index for facet v1 vertex
  34859. var b1z = 0; // z partitioning index for facet v1 vertex
  34860. var b2x = 0; // X partitioning index for facet v2 vertex
  34861. var b2y = 0; // Y partitioning index for facet v2 vertex
  34862. var b2z = 0; // Z partitioning index for facet v2 vertex
  34863. var b3x = 0; // X partitioning index for facet v3 vertex
  34864. var b3y = 0; // Y partitioning index for facet v3 vertex
  34865. var b3z = 0; // Z partitioning index for facet v3 vertex
  34866. var block_idx_o = 0; // facet barycenter block index
  34867. var block_idx_v1 = 0; // v1 vertex block index
  34868. var block_idx_v2 = 0; // v2 vertex block index
  34869. var block_idx_v3 = 0; // v3 vertex block index
  34870. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  34871. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  34872. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  34873. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  34874. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  34875. subSq = options.subDiv.max * options.subDiv.max;
  34876. options.facetPartitioning.length = 0;
  34877. }
  34878. // reset the normals
  34879. for (index = 0; index < positions.length; index++) {
  34880. normals[index] = 0.0;
  34881. }
  34882. // Loop : 1 indice triplet = 1 facet
  34883. var nbFaces = (indices.length / 3) | 0;
  34884. for (index = 0; index < nbFaces; index++) {
  34885. // get the indexes of the coordinates of each vertex of the facet
  34886. v1x = indices[index * 3] * 3;
  34887. v1y = v1x + 1;
  34888. v1z = v1x + 2;
  34889. v2x = indices[index * 3 + 1] * 3;
  34890. v2y = v2x + 1;
  34891. v2z = v2x + 2;
  34892. v3x = indices[index * 3 + 2] * 3;
  34893. v3y = v3x + 1;
  34894. v3z = v3x + 2;
  34895. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  34896. p1p2y = positions[v1y] - positions[v2y];
  34897. p1p2z = positions[v1z] - positions[v2z];
  34898. p3p2x = positions[v3x] - positions[v2x];
  34899. p3p2y = positions[v3y] - positions[v2y];
  34900. p3p2z = positions[v3z] - positions[v2z];
  34901. // compute the face normal with the cross product
  34902. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  34903. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  34904. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  34905. // normalize this normal and store it in the array facetData
  34906. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34907. length = (length === 0) ? 1.0 : length;
  34908. faceNormalx /= length;
  34909. faceNormaly /= length;
  34910. faceNormalz /= length;
  34911. if (computeFacetNormals && options) {
  34912. options.facetNormals[index].x = faceNormalx;
  34913. options.facetNormals[index].y = faceNormaly;
  34914. options.facetNormals[index].z = faceNormalz;
  34915. }
  34916. if (computeFacetPositions && options) {
  34917. // compute and the facet barycenter coordinates in the array facetPositions
  34918. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  34919. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  34920. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  34921. }
  34922. if (computeFacetPartitioning && options) {
  34923. // store the facet indexes in arrays in the main facetPartitioning array :
  34924. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  34925. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  34926. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  34927. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  34928. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34929. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34930. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34931. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34932. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34933. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34934. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  34935. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  34936. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  34937. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  34938. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  34939. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  34940. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  34941. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  34942. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  34943. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  34944. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  34945. // push each facet index in each block containing the vertex
  34946. options.facetPartitioning[block_idx_v1].push(index);
  34947. if (block_idx_v2 != block_idx_v1) {
  34948. options.facetPartitioning[block_idx_v2].push(index);
  34949. }
  34950. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  34951. options.facetPartitioning[block_idx_v3].push(index);
  34952. }
  34953. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  34954. options.facetPartitioning[block_idx_o].push(index);
  34955. }
  34956. }
  34957. if (computeDepthSort && options && options.facetPositions) {
  34958. var dsf = depthSortedFacets[index];
  34959. dsf.ind = index * 3;
  34960. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  34961. }
  34962. // compute the normals anyway
  34963. normals[v1x] += faceNormalx; // accumulate all the normals per face
  34964. normals[v1y] += faceNormaly;
  34965. normals[v1z] += faceNormalz;
  34966. normals[v2x] += faceNormalx;
  34967. normals[v2y] += faceNormaly;
  34968. normals[v2z] += faceNormalz;
  34969. normals[v3x] += faceNormalx;
  34970. normals[v3y] += faceNormaly;
  34971. normals[v3z] += faceNormalz;
  34972. }
  34973. // last normalization of each normal
  34974. for (index = 0; index < normals.length / 3; index++) {
  34975. faceNormalx = normals[index * 3];
  34976. faceNormaly = normals[index * 3 + 1];
  34977. faceNormalz = normals[index * 3 + 2];
  34978. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34979. length = (length === 0) ? 1.0 : length;
  34980. faceNormalx /= length;
  34981. faceNormaly /= length;
  34982. faceNormalz /= length;
  34983. normals[index * 3] = faceNormalx;
  34984. normals[index * 3 + 1] = faceNormaly;
  34985. normals[index * 3 + 2] = faceNormalz;
  34986. }
  34987. };
  34988. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  34989. var li = indices.length;
  34990. var ln = normals.length;
  34991. var i;
  34992. var n;
  34993. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34994. switch (sideOrientation) {
  34995. case BABYLON.Mesh.FRONTSIDE:
  34996. // nothing changed
  34997. break;
  34998. case BABYLON.Mesh.BACKSIDE:
  34999. var tmp;
  35000. // indices
  35001. for (i = 0; i < li; i += 3) {
  35002. tmp = indices[i];
  35003. indices[i] = indices[i + 2];
  35004. indices[i + 2] = tmp;
  35005. }
  35006. // normals
  35007. for (n = 0; n < ln; n++) {
  35008. normals[n] = -normals[n];
  35009. }
  35010. break;
  35011. case BABYLON.Mesh.DOUBLESIDE:
  35012. // positions
  35013. var lp = positions.length;
  35014. var l = lp / 3;
  35015. for (var p = 0; p < lp; p++) {
  35016. positions[lp + p] = positions[p];
  35017. }
  35018. // indices
  35019. for (i = 0; i < li; i += 3) {
  35020. indices[i + li] = indices[i + 2] + l;
  35021. indices[i + 1 + li] = indices[i + 1] + l;
  35022. indices[i + 2 + li] = indices[i] + l;
  35023. }
  35024. // normals
  35025. for (n = 0; n < ln; n++) {
  35026. normals[ln + n] = -normals[n];
  35027. }
  35028. // uvs
  35029. var lu = uvs.length;
  35030. var u = 0;
  35031. for (u = 0; u < lu; u++) {
  35032. uvs[u + lu] = uvs[u];
  35033. }
  35034. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  35035. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  35036. u = 0;
  35037. for (i = 0; i < lu / 2; i++) {
  35038. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  35039. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  35040. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  35041. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  35042. u += 2;
  35043. }
  35044. break;
  35045. }
  35046. };
  35047. /**
  35048. * Creates a new VertexData from the imported parameters.
  35049. */
  35050. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  35051. var vertexData = new VertexData();
  35052. // positions
  35053. var positions = parsedVertexData.positions;
  35054. if (positions) {
  35055. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  35056. }
  35057. // normals
  35058. var normals = parsedVertexData.normals;
  35059. if (normals) {
  35060. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  35061. }
  35062. // tangents
  35063. var tangents = parsedVertexData.tangents;
  35064. if (tangents) {
  35065. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  35066. }
  35067. // uvs
  35068. var uvs = parsedVertexData.uvs;
  35069. if (uvs) {
  35070. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  35071. }
  35072. // uv2s
  35073. var uv2s = parsedVertexData.uv2s;
  35074. if (uv2s) {
  35075. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  35076. }
  35077. // uv3s
  35078. var uv3s = parsedVertexData.uv3s;
  35079. if (uv3s) {
  35080. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  35081. }
  35082. // uv4s
  35083. var uv4s = parsedVertexData.uv4s;
  35084. if (uv4s) {
  35085. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  35086. }
  35087. // uv5s
  35088. var uv5s = parsedVertexData.uv5s;
  35089. if (uv5s) {
  35090. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  35091. }
  35092. // uv6s
  35093. var uv6s = parsedVertexData.uv6s;
  35094. if (uv6s) {
  35095. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  35096. }
  35097. // colors
  35098. var colors = parsedVertexData.colors;
  35099. if (colors) {
  35100. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  35101. }
  35102. // matricesIndices
  35103. var matricesIndices = parsedVertexData.matricesIndices;
  35104. if (matricesIndices) {
  35105. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  35106. }
  35107. // matricesWeights
  35108. var matricesWeights = parsedVertexData.matricesWeights;
  35109. if (matricesWeights) {
  35110. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  35111. }
  35112. // indices
  35113. var indices = parsedVertexData.indices;
  35114. if (indices) {
  35115. vertexData.indices = indices;
  35116. }
  35117. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  35118. };
  35119. return VertexData;
  35120. }());
  35121. BABYLON.VertexData = VertexData;
  35122. })(BABYLON || (BABYLON = {}));
  35123. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  35124. "use strict";
  35125. var BABYLON;
  35126. (function (BABYLON) {
  35127. /**
  35128. * Class used to store geometry data (vertex buffers + index buffer)
  35129. */
  35130. var Geometry = /** @class */ (function () {
  35131. /**
  35132. * Creates a new geometry
  35133. * @param id defines the unique ID
  35134. * @param scene defines the hosting scene
  35135. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  35136. * @param updatable defines if geometry must be updatable (false by default)
  35137. * @param mesh defines the mesh that will be associated with the geometry
  35138. */
  35139. function Geometry(id, scene, vertexData, updatable, mesh) {
  35140. if (updatable === void 0) { updatable = false; }
  35141. if (mesh === void 0) { mesh = null; }
  35142. /**
  35143. * Gets the delay loading state of the geometry (none by default which means not delayed)
  35144. */
  35145. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35146. this._totalVertices = 0;
  35147. this._isDisposed = false;
  35148. this._indexBufferIsUpdatable = false;
  35149. this.id = id;
  35150. this._engine = scene.getEngine();
  35151. this._meshes = [];
  35152. this._scene = scene;
  35153. //Init vertex buffer cache
  35154. this._vertexBuffers = {};
  35155. this._indices = [];
  35156. this._updatable = updatable;
  35157. // vertexData
  35158. if (vertexData) {
  35159. this.setAllVerticesData(vertexData, updatable);
  35160. }
  35161. else {
  35162. this._totalVertices = 0;
  35163. this._indices = [];
  35164. }
  35165. if (this._engine.getCaps().vertexArrayObject) {
  35166. this._vertexArrayObjects = {};
  35167. }
  35168. // applyToMesh
  35169. if (mesh) {
  35170. if (mesh.getClassName() === "LinesMesh") {
  35171. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  35172. this.updateExtend();
  35173. }
  35174. this.applyToMesh(mesh);
  35175. mesh.computeWorldMatrix(true);
  35176. }
  35177. }
  35178. Object.defineProperty(Geometry.prototype, "boundingBias", {
  35179. /**
  35180. * 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
  35181. */
  35182. get: function () {
  35183. return this._boundingBias;
  35184. },
  35185. /**
  35186. * 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
  35187. */
  35188. set: function (value) {
  35189. if (this._boundingBias && this._boundingBias.equals(value)) {
  35190. return;
  35191. }
  35192. this._boundingBias = value.clone();
  35193. this.updateBoundingInfo(true, null);
  35194. },
  35195. enumerable: true,
  35196. configurable: true
  35197. });
  35198. /**
  35199. * Static function used to attach a new empty geometry to a mesh
  35200. * @param mesh defines the mesh to attach the geometry to
  35201. * @returns the new {BABYLON.Geometry}
  35202. */
  35203. Geometry.CreateGeometryForMesh = function (mesh) {
  35204. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  35205. geometry.applyToMesh(mesh);
  35206. return geometry;
  35207. };
  35208. Object.defineProperty(Geometry.prototype, "extend", {
  35209. /**
  35210. * Gets the current extend of the geometry
  35211. */
  35212. get: function () {
  35213. return this._extend;
  35214. },
  35215. enumerable: true,
  35216. configurable: true
  35217. });
  35218. /**
  35219. * Gets the hosting scene
  35220. * @returns the hosting {BABYLON.Scene}
  35221. */
  35222. Geometry.prototype.getScene = function () {
  35223. return this._scene;
  35224. };
  35225. /**
  35226. * Gets the hosting engine
  35227. * @returns the hosting {BABYLON.Engine}
  35228. */
  35229. Geometry.prototype.getEngine = function () {
  35230. return this._engine;
  35231. };
  35232. /**
  35233. * Defines if the geometry is ready to use
  35234. * @returns true if the geometry is ready to be used
  35235. */
  35236. Geometry.prototype.isReady = function () {
  35237. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  35238. };
  35239. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  35240. /**
  35241. * Gets a value indicating that the geometry should not be serialized
  35242. */
  35243. get: function () {
  35244. for (var index = 0; index < this._meshes.length; index++) {
  35245. if (!this._meshes[index].doNotSerialize) {
  35246. return false;
  35247. }
  35248. }
  35249. return true;
  35250. },
  35251. enumerable: true,
  35252. configurable: true
  35253. });
  35254. /** @ignore */
  35255. Geometry.prototype._rebuild = function () {
  35256. if (this._vertexArrayObjects) {
  35257. this._vertexArrayObjects = {};
  35258. }
  35259. // Index buffer
  35260. if (this._meshes.length !== 0 && this._indices) {
  35261. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35262. }
  35263. // Vertex buffers
  35264. for (var key in this._vertexBuffers) {
  35265. var vertexBuffer = this._vertexBuffers[key];
  35266. vertexBuffer._rebuild();
  35267. }
  35268. };
  35269. /**
  35270. * Affects all gemetry data in one call
  35271. * @param vertexData defines the geometry data
  35272. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  35273. */
  35274. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  35275. vertexData.applyToGeometry(this, updatable);
  35276. this.notifyUpdate();
  35277. };
  35278. /**
  35279. * Set specific vertex data
  35280. * @param kind defines the data kind (Position, normal, etc...)
  35281. * @param data defines the vertex data to use
  35282. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  35283. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  35284. */
  35285. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  35286. if (updatable === void 0) { updatable = false; }
  35287. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  35288. this.setVerticesBuffer(buffer);
  35289. };
  35290. /**
  35291. * Removes a specific vertex data
  35292. * @param kind defines the data kind (Position, normal, etc...)
  35293. */
  35294. Geometry.prototype.removeVerticesData = function (kind) {
  35295. if (this._vertexBuffers[kind]) {
  35296. this._vertexBuffers[kind].dispose();
  35297. delete this._vertexBuffers[kind];
  35298. }
  35299. };
  35300. /**
  35301. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  35302. * @param buffer defines the vertex buffer to use
  35303. */
  35304. Geometry.prototype.setVerticesBuffer = function (buffer) {
  35305. var kind = buffer.getKind();
  35306. if (this._vertexBuffers[kind]) {
  35307. this._vertexBuffers[kind].dispose();
  35308. }
  35309. this._vertexBuffers[kind] = buffer;
  35310. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35311. var data = buffer.getData();
  35312. var stride = buffer.getStrideSize();
  35313. this._totalVertices = data.length / stride;
  35314. this.updateExtend(data, stride);
  35315. this._resetPointsArrayCache();
  35316. var meshes = this._meshes;
  35317. var numOfMeshes = meshes.length;
  35318. for (var index = 0; index < numOfMeshes; index++) {
  35319. var mesh = meshes[index];
  35320. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35321. mesh._createGlobalSubMesh(false);
  35322. mesh.computeWorldMatrix(true);
  35323. }
  35324. }
  35325. this.notifyUpdate(kind);
  35326. if (this._vertexArrayObjects) {
  35327. this._disposeVertexArrayObjects();
  35328. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  35329. }
  35330. };
  35331. /**
  35332. * Update a specific vertex buffer
  35333. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  35334. * It will do nothing if the buffer is not updatable
  35335. * @param kind defines the data kind (Position, normal, etc...)
  35336. * @param data defines the data to use
  35337. * @param offset defines the offset in the target buffer where to store the data
  35338. */
  35339. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  35340. var vertexBuffer = this.getVertexBuffer(kind);
  35341. if (!vertexBuffer) {
  35342. return;
  35343. }
  35344. vertexBuffer.updateDirectly(data, offset);
  35345. this.notifyUpdate(kind);
  35346. };
  35347. /**
  35348. * Update a specific vertex buffer
  35349. * This function will create a new buffer if the current one is not updatable
  35350. * @param kind defines the data kind (Position, normal, etc...)
  35351. * @param data defines the data to use
  35352. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  35353. */
  35354. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  35355. if (updateExtends === void 0) { updateExtends = false; }
  35356. var vertexBuffer = this.getVertexBuffer(kind);
  35357. if (!vertexBuffer) {
  35358. return;
  35359. }
  35360. vertexBuffer.update(data);
  35361. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35362. var stride = vertexBuffer.getStrideSize();
  35363. this._totalVertices = data.length / stride;
  35364. this.updateBoundingInfo(updateExtends, data);
  35365. }
  35366. this.notifyUpdate(kind);
  35367. };
  35368. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  35369. if (updateExtends) {
  35370. this.updateExtend(data);
  35371. }
  35372. var meshes = this._meshes;
  35373. var numOfMeshes = meshes.length;
  35374. this._resetPointsArrayCache();
  35375. for (var index = 0; index < numOfMeshes; index++) {
  35376. var mesh = meshes[index];
  35377. if (updateExtends) {
  35378. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35379. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  35380. var subMesh = mesh.subMeshes[subIndex];
  35381. subMesh.refreshBoundingInfo();
  35382. }
  35383. }
  35384. }
  35385. };
  35386. /** @ignore */
  35387. Geometry.prototype._bind = function (effect, indexToBind) {
  35388. if (!effect) {
  35389. return;
  35390. }
  35391. if (indexToBind === undefined) {
  35392. indexToBind = this._indexBuffer;
  35393. }
  35394. var vbs = this.getVertexBuffers();
  35395. if (!vbs) {
  35396. return;
  35397. }
  35398. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  35399. this._engine.bindBuffers(vbs, indexToBind, effect);
  35400. return;
  35401. }
  35402. // Using VAO
  35403. if (!this._vertexArrayObjects[effect.key]) {
  35404. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  35405. }
  35406. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  35407. };
  35408. /**
  35409. * Gets total number of vertices
  35410. * @returns the total number of vertices
  35411. */
  35412. Geometry.prototype.getTotalVertices = function () {
  35413. if (!this.isReady()) {
  35414. return 0;
  35415. }
  35416. return this._totalVertices;
  35417. };
  35418. /**
  35419. * Gets a specific vertex data attached to this geometry
  35420. * @param kind defines the data kind (Position, normal, etc...)
  35421. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  35422. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  35423. * @returns a float array containing vertex data
  35424. */
  35425. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  35426. var vertexBuffer = this.getVertexBuffer(kind);
  35427. if (!vertexBuffer) {
  35428. return null;
  35429. }
  35430. var orig = vertexBuffer.getData();
  35431. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  35432. return orig;
  35433. }
  35434. else {
  35435. var len = orig.length;
  35436. var copy = [];
  35437. for (var i = 0; i < len; i++) {
  35438. copy.push(orig[i]);
  35439. }
  35440. return copy;
  35441. }
  35442. };
  35443. /**
  35444. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  35445. * @param kind defines the data kind (Position, normal, etc...)
  35446. * @returns true if the vertex buffer with the specified kind is updatable
  35447. */
  35448. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  35449. var vb = this._vertexBuffers[kind];
  35450. if (!vb) {
  35451. return false;
  35452. }
  35453. return vb.isUpdatable();
  35454. };
  35455. /**
  35456. * Gets a specific vertex buffer
  35457. * @param kind defines the data kind (Position, normal, etc...)
  35458. * @returns a {BABYLON.VertexBuffer}
  35459. */
  35460. Geometry.prototype.getVertexBuffer = function (kind) {
  35461. if (!this.isReady()) {
  35462. return null;
  35463. }
  35464. return this._vertexBuffers[kind];
  35465. };
  35466. /**
  35467. * Returns all vertex buffers
  35468. * @return an object holding all vertex buffers indexed by kind
  35469. */
  35470. Geometry.prototype.getVertexBuffers = function () {
  35471. if (!this.isReady()) {
  35472. return null;
  35473. }
  35474. return this._vertexBuffers;
  35475. };
  35476. /**
  35477. * Gets a boolean indicating if specific vertex buffer is present
  35478. * @param kind defines the data kind (Position, normal, etc...)
  35479. * @returns true if data is present
  35480. */
  35481. Geometry.prototype.isVerticesDataPresent = function (kind) {
  35482. if (!this._vertexBuffers) {
  35483. if (this._delayInfo) {
  35484. return this._delayInfo.indexOf(kind) !== -1;
  35485. }
  35486. return false;
  35487. }
  35488. return this._vertexBuffers[kind] !== undefined;
  35489. };
  35490. /**
  35491. * Gets a list of all attached data kinds (Position, normal, etc...)
  35492. * @returns a list of string containing all kinds
  35493. */
  35494. Geometry.prototype.getVerticesDataKinds = function () {
  35495. var result = [];
  35496. var kind;
  35497. if (!this._vertexBuffers && this._delayInfo) {
  35498. for (kind in this._delayInfo) {
  35499. result.push(kind);
  35500. }
  35501. }
  35502. else {
  35503. for (kind in this._vertexBuffers) {
  35504. result.push(kind);
  35505. }
  35506. }
  35507. return result;
  35508. };
  35509. /**
  35510. * Update index buffer
  35511. * @param indices defines the indices to store in the index buffer
  35512. * @param offset defines the offset in the target buffer where to store the data
  35513. */
  35514. Geometry.prototype.updateIndices = function (indices, offset) {
  35515. if (!this._indexBuffer) {
  35516. return;
  35517. }
  35518. if (!this._indexBufferIsUpdatable) {
  35519. this.setIndices(indices, null, true);
  35520. }
  35521. else {
  35522. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  35523. }
  35524. };
  35525. /**
  35526. * Creates a new index buffer
  35527. * @param indices defines the indices to store in the index buffer
  35528. * @param totalVertices defines the total number of vertices (could be null)
  35529. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  35530. */
  35531. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  35532. if (totalVertices === void 0) { totalVertices = null; }
  35533. if (updatable === void 0) { updatable = false; }
  35534. if (this._indexBuffer) {
  35535. this._engine._releaseBuffer(this._indexBuffer);
  35536. }
  35537. this._disposeVertexArrayObjects();
  35538. this._indices = indices;
  35539. this._indexBufferIsUpdatable = updatable;
  35540. if (this._meshes.length !== 0 && this._indices) {
  35541. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  35542. }
  35543. if (totalVertices != undefined) {
  35544. this._totalVertices = totalVertices;
  35545. }
  35546. var meshes = this._meshes;
  35547. var numOfMeshes = meshes.length;
  35548. for (var index = 0; index < numOfMeshes; index++) {
  35549. meshes[index]._createGlobalSubMesh(true);
  35550. }
  35551. this.notifyUpdate();
  35552. };
  35553. /**
  35554. * Return the total number of indices
  35555. * @returns the total number of indices
  35556. */
  35557. Geometry.prototype.getTotalIndices = function () {
  35558. if (!this.isReady()) {
  35559. return 0;
  35560. }
  35561. return this._indices.length;
  35562. };
  35563. /**
  35564. * Gets the index buffer array
  35565. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  35566. * @returns the index buffer array
  35567. */
  35568. Geometry.prototype.getIndices = function (copyWhenShared) {
  35569. if (!this.isReady()) {
  35570. return null;
  35571. }
  35572. var orig = this._indices;
  35573. if (!copyWhenShared || this._meshes.length === 1) {
  35574. return orig;
  35575. }
  35576. else {
  35577. var len = orig.length;
  35578. var copy = [];
  35579. for (var i = 0; i < len; i++) {
  35580. copy.push(orig[i]);
  35581. }
  35582. return copy;
  35583. }
  35584. };
  35585. /**
  35586. * Gets the index buffer
  35587. * @return the index buffer
  35588. */
  35589. Geometry.prototype.getIndexBuffer = function () {
  35590. if (!this.isReady()) {
  35591. return null;
  35592. }
  35593. return this._indexBuffer;
  35594. };
  35595. /** @ignore */
  35596. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  35597. if (effect === void 0) { effect = null; }
  35598. if (!effect || !this._vertexArrayObjects) {
  35599. return;
  35600. }
  35601. if (this._vertexArrayObjects[effect.key]) {
  35602. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  35603. delete this._vertexArrayObjects[effect.key];
  35604. }
  35605. };
  35606. /**
  35607. * Release the associated resources for a specific mesh
  35608. * @param mesh defines the source mesh
  35609. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  35610. */
  35611. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  35612. var meshes = this._meshes;
  35613. var index = meshes.indexOf(mesh);
  35614. if (index === -1) {
  35615. return;
  35616. }
  35617. meshes.splice(index, 1);
  35618. mesh._geometry = null;
  35619. if (meshes.length === 0 && shouldDispose) {
  35620. this.dispose();
  35621. }
  35622. };
  35623. /**
  35624. * Apply current geometry to a given mesh
  35625. * @param mesh defines the mesh to apply geometry to
  35626. */
  35627. Geometry.prototype.applyToMesh = function (mesh) {
  35628. if (mesh._geometry === this) {
  35629. return;
  35630. }
  35631. var previousGeometry = mesh._geometry;
  35632. if (previousGeometry) {
  35633. previousGeometry.releaseForMesh(mesh);
  35634. }
  35635. var meshes = this._meshes;
  35636. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  35637. mesh._geometry = this;
  35638. this._scene.pushGeometry(this);
  35639. meshes.push(mesh);
  35640. if (this.isReady()) {
  35641. this._applyToMesh(mesh);
  35642. }
  35643. else {
  35644. mesh._boundingInfo = this._boundingInfo;
  35645. }
  35646. };
  35647. Geometry.prototype.updateExtend = function (data, stride) {
  35648. if (data === void 0) { data = null; }
  35649. if (!data) {
  35650. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  35651. }
  35652. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  35653. };
  35654. Geometry.prototype._applyToMesh = function (mesh) {
  35655. var numOfMeshes = this._meshes.length;
  35656. // vertexBuffers
  35657. for (var kind in this._vertexBuffers) {
  35658. if (numOfMeshes === 1) {
  35659. this._vertexBuffers[kind].create();
  35660. }
  35661. var buffer = this._vertexBuffers[kind].getBuffer();
  35662. if (buffer)
  35663. buffer.references = numOfMeshes;
  35664. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35665. if (!this._extend) {
  35666. this.updateExtend(this._vertexBuffers[kind].getData());
  35667. }
  35668. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35669. mesh._createGlobalSubMesh(false);
  35670. //bounding info was just created again, world matrix should be applied again.
  35671. mesh._updateBoundingInfo();
  35672. }
  35673. }
  35674. // indexBuffer
  35675. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  35676. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35677. }
  35678. if (this._indexBuffer) {
  35679. this._indexBuffer.references = numOfMeshes;
  35680. }
  35681. };
  35682. Geometry.prototype.notifyUpdate = function (kind) {
  35683. if (this.onGeometryUpdated) {
  35684. this.onGeometryUpdated(this, kind);
  35685. }
  35686. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  35687. var mesh = _a[_i];
  35688. mesh._markSubMeshesAsAttributesDirty();
  35689. }
  35690. };
  35691. /**
  35692. * Load the geometry if it was flagged as delay loaded
  35693. * @param scene defines the hosting scene
  35694. * @param onLoaded defines a callback called when the geometry is loaded
  35695. */
  35696. Geometry.prototype.load = function (scene, onLoaded) {
  35697. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  35698. return;
  35699. }
  35700. if (this.isReady()) {
  35701. if (onLoaded) {
  35702. onLoaded();
  35703. }
  35704. return;
  35705. }
  35706. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  35707. this._queueLoad(scene, onLoaded);
  35708. };
  35709. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  35710. var _this = this;
  35711. if (!this.delayLoadingFile) {
  35712. return;
  35713. }
  35714. scene._addPendingData(this);
  35715. scene._loadFile(this.delayLoadingFile, function (data) {
  35716. if (!_this._delayLoadingFunction) {
  35717. return;
  35718. }
  35719. _this._delayLoadingFunction(JSON.parse(data), _this);
  35720. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  35721. _this._delayInfo = [];
  35722. scene._removePendingData(_this);
  35723. var meshes = _this._meshes;
  35724. var numOfMeshes = meshes.length;
  35725. for (var index = 0; index < numOfMeshes; index++) {
  35726. _this._applyToMesh(meshes[index]);
  35727. }
  35728. if (onLoaded) {
  35729. onLoaded();
  35730. }
  35731. }, undefined, true);
  35732. };
  35733. /**
  35734. * Invert the geometry to move from a right handed system to a left handed one.
  35735. */
  35736. Geometry.prototype.toLeftHanded = function () {
  35737. // Flip faces
  35738. var tIndices = this.getIndices(false);
  35739. if (tIndices != null && tIndices.length > 0) {
  35740. for (var i = 0; i < tIndices.length; i += 3) {
  35741. var tTemp = tIndices[i + 0];
  35742. tIndices[i + 0] = tIndices[i + 2];
  35743. tIndices[i + 2] = tTemp;
  35744. }
  35745. this.setIndices(tIndices);
  35746. }
  35747. // Negate position.z
  35748. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  35749. if (tPositions != null && tPositions.length > 0) {
  35750. for (var i = 0; i < tPositions.length; i += 3) {
  35751. tPositions[i + 2] = -tPositions[i + 2];
  35752. }
  35753. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  35754. }
  35755. // Negate normal.z
  35756. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  35757. if (tNormals != null && tNormals.length > 0) {
  35758. for (var i = 0; i < tNormals.length; i += 3) {
  35759. tNormals[i + 2] = -tNormals[i + 2];
  35760. }
  35761. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  35762. }
  35763. };
  35764. // Cache
  35765. /** @ignore */
  35766. Geometry.prototype._resetPointsArrayCache = function () {
  35767. this._positions = null;
  35768. };
  35769. /** @ignore */
  35770. Geometry.prototype._generatePointsArray = function () {
  35771. if (this._positions)
  35772. return true;
  35773. this._positions = [];
  35774. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35775. if (!data) {
  35776. return false;
  35777. }
  35778. for (var index = 0; index < data.length; index += 3) {
  35779. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  35780. }
  35781. return true;
  35782. };
  35783. /**
  35784. * Gets a value indicating if the geometry is disposed
  35785. * @returns true if the geometry was disposed
  35786. */
  35787. Geometry.prototype.isDisposed = function () {
  35788. return this._isDisposed;
  35789. };
  35790. Geometry.prototype._disposeVertexArrayObjects = function () {
  35791. if (this._vertexArrayObjects) {
  35792. for (var kind in this._vertexArrayObjects) {
  35793. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  35794. }
  35795. this._vertexArrayObjects = {};
  35796. }
  35797. };
  35798. /**
  35799. * Free all associated resources
  35800. */
  35801. Geometry.prototype.dispose = function () {
  35802. var meshes = this._meshes;
  35803. var numOfMeshes = meshes.length;
  35804. var index;
  35805. for (index = 0; index < numOfMeshes; index++) {
  35806. this.releaseForMesh(meshes[index]);
  35807. }
  35808. this._meshes = [];
  35809. this._disposeVertexArrayObjects();
  35810. for (var kind in this._vertexBuffers) {
  35811. this._vertexBuffers[kind].dispose();
  35812. }
  35813. this._vertexBuffers = {};
  35814. this._totalVertices = 0;
  35815. if (this._indexBuffer) {
  35816. this._engine._releaseBuffer(this._indexBuffer);
  35817. }
  35818. this._indexBuffer = null;
  35819. this._indices = [];
  35820. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35821. this.delayLoadingFile = null;
  35822. this._delayLoadingFunction = null;
  35823. this._delayInfo = [];
  35824. this._boundingInfo = null;
  35825. this._scene.removeGeometry(this);
  35826. this._isDisposed = true;
  35827. };
  35828. /**
  35829. * Clone the current geometry into a new geometry
  35830. * @param id defines the unique ID of the new geometry
  35831. * @returns a new geometry object
  35832. */
  35833. Geometry.prototype.copy = function (id) {
  35834. var vertexData = new BABYLON.VertexData();
  35835. vertexData.indices = [];
  35836. var indices = this.getIndices();
  35837. if (indices) {
  35838. for (var index = 0; index < indices.length; index++) {
  35839. vertexData.indices.push(indices[index]);
  35840. }
  35841. }
  35842. var updatable = false;
  35843. var stopChecking = false;
  35844. var kind;
  35845. for (kind in this._vertexBuffers) {
  35846. // using slice() to make a copy of the array and not just reference it
  35847. var data = this.getVerticesData(kind);
  35848. if (data instanceof Float32Array) {
  35849. vertexData.set(new Float32Array(data), kind);
  35850. }
  35851. else {
  35852. vertexData.set(data.slice(0), kind);
  35853. }
  35854. if (!stopChecking) {
  35855. var vb = this.getVertexBuffer(kind);
  35856. if (vb) {
  35857. updatable = vb.isUpdatable();
  35858. stopChecking = !updatable;
  35859. }
  35860. }
  35861. }
  35862. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  35863. geometry.delayLoadState = this.delayLoadState;
  35864. geometry.delayLoadingFile = this.delayLoadingFile;
  35865. geometry._delayLoadingFunction = this._delayLoadingFunction;
  35866. for (kind in this._delayInfo) {
  35867. geometry._delayInfo = geometry._delayInfo || [];
  35868. geometry._delayInfo.push(kind);
  35869. }
  35870. // Bounding info
  35871. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35872. return geometry;
  35873. };
  35874. /**
  35875. * Serialize the current geometry info (and not the vertices data) into a JSON object
  35876. * @return a JSON representation of the current geometry data (without the vertices data)
  35877. */
  35878. Geometry.prototype.serialize = function () {
  35879. var serializationObject = {};
  35880. serializationObject.id = this.id;
  35881. serializationObject.updatable = this._updatable;
  35882. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  35883. serializationObject.tags = BABYLON.Tags.GetTags(this);
  35884. }
  35885. return serializationObject;
  35886. };
  35887. Geometry.prototype.toNumberArray = function (origin) {
  35888. if (Array.isArray(origin)) {
  35889. return origin;
  35890. }
  35891. else {
  35892. return Array.prototype.slice.call(origin);
  35893. }
  35894. };
  35895. /**
  35896. * Serialize all vertices data into a JSON oject
  35897. * @returns a JSON representation of the current geometry data
  35898. */
  35899. Geometry.prototype.serializeVerticeData = function () {
  35900. var serializationObject = this.serialize();
  35901. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35902. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  35903. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  35904. serializationObject.positions._updatable = true;
  35905. }
  35906. }
  35907. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35908. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  35909. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  35910. serializationObject.normals._updatable = true;
  35911. }
  35912. }
  35913. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  35914. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  35915. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  35916. serializationObject.tangets._updatable = true;
  35917. }
  35918. }
  35919. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35920. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  35921. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  35922. serializationObject.uvs._updatable = true;
  35923. }
  35924. }
  35925. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35926. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  35927. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  35928. serializationObject.uv2s._updatable = true;
  35929. }
  35930. }
  35931. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  35932. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  35933. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  35934. serializationObject.uv3s._updatable = true;
  35935. }
  35936. }
  35937. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  35938. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  35939. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  35940. serializationObject.uv4s._updatable = true;
  35941. }
  35942. }
  35943. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  35944. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  35945. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  35946. serializationObject.uv5s._updatable = true;
  35947. }
  35948. }
  35949. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  35950. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  35951. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  35952. serializationObject.uv6s._updatable = true;
  35953. }
  35954. }
  35955. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  35956. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  35957. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  35958. serializationObject.colors._updatable = true;
  35959. }
  35960. }
  35961. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35962. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  35963. serializationObject.matricesIndices._isExpanded = true;
  35964. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35965. serializationObject.matricesIndices._updatable = true;
  35966. }
  35967. }
  35968. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35969. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  35970. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35971. serializationObject.matricesWeights._updatable = true;
  35972. }
  35973. }
  35974. serializationObject.indices = this.toNumberArray(this.getIndices());
  35975. return serializationObject;
  35976. };
  35977. // Statics
  35978. /**
  35979. * Extracts a clone of a mesh geometry
  35980. * @param mesh defines the source mesh
  35981. * @param id defines the unique ID of the new geometry object
  35982. * @returns the new geometry object
  35983. */
  35984. Geometry.ExtractFromMesh = function (mesh, id) {
  35985. var geometry = mesh._geometry;
  35986. if (!geometry) {
  35987. return null;
  35988. }
  35989. return geometry.copy(id);
  35990. };
  35991. /**
  35992. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  35993. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  35994. * Be aware Math.random() could cause collisions, but:
  35995. * "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"
  35996. * @returns a string containing a new GUID
  35997. */
  35998. Geometry.RandomId = function () {
  35999. return BABYLON.Tools.RandomId();
  36000. };
  36001. /** @ignore */
  36002. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  36003. var scene = mesh.getScene();
  36004. // Geometry
  36005. var geometryId = parsedGeometry.geometryId;
  36006. if (geometryId) {
  36007. var geometry = scene.getGeometryByID(geometryId);
  36008. if (geometry) {
  36009. geometry.applyToMesh(mesh);
  36010. }
  36011. }
  36012. else if (parsedGeometry instanceof ArrayBuffer) {
  36013. var binaryInfo = mesh._binaryInfo;
  36014. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  36015. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  36016. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  36017. }
  36018. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  36019. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  36020. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  36021. }
  36022. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  36023. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  36024. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  36025. }
  36026. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  36027. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  36028. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  36029. }
  36030. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  36031. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  36032. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  36033. }
  36034. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  36035. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  36036. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  36037. }
  36038. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  36039. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  36040. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  36041. }
  36042. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  36043. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  36044. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  36045. }
  36046. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  36047. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  36048. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  36049. }
  36050. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  36051. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  36052. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  36053. }
  36054. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  36055. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  36056. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  36057. }
  36058. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  36059. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  36060. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  36061. }
  36062. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  36063. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  36064. mesh.setIndices(indicesData, null);
  36065. }
  36066. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  36067. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  36068. mesh.subMeshes = [];
  36069. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  36070. var materialIndex = subMeshesData[(i * 5) + 0];
  36071. var verticesStart = subMeshesData[(i * 5) + 1];
  36072. var verticesCount = subMeshesData[(i * 5) + 2];
  36073. var indexStart = subMeshesData[(i * 5) + 3];
  36074. var indexCount = subMeshesData[(i * 5) + 4];
  36075. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  36076. }
  36077. }
  36078. }
  36079. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  36080. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  36081. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  36082. if (parsedGeometry.tangents) {
  36083. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  36084. }
  36085. if (parsedGeometry.uvs) {
  36086. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  36087. }
  36088. if (parsedGeometry.uvs2) {
  36089. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  36090. }
  36091. if (parsedGeometry.uvs3) {
  36092. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  36093. }
  36094. if (parsedGeometry.uvs4) {
  36095. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  36096. }
  36097. if (parsedGeometry.uvs5) {
  36098. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  36099. }
  36100. if (parsedGeometry.uvs6) {
  36101. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  36102. }
  36103. if (parsedGeometry.colors) {
  36104. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  36105. }
  36106. if (parsedGeometry.matricesIndices) {
  36107. if (!parsedGeometry.matricesIndices._isExpanded) {
  36108. var floatIndices = [];
  36109. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  36110. var matricesIndex = parsedGeometry.matricesIndices[i];
  36111. floatIndices.push(matricesIndex & 0x000000FF);
  36112. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  36113. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  36114. floatIndices.push(matricesIndex >> 24);
  36115. }
  36116. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  36117. }
  36118. else {
  36119. delete parsedGeometry.matricesIndices._isExpanded;
  36120. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  36121. }
  36122. }
  36123. if (parsedGeometry.matricesIndicesExtra) {
  36124. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  36125. var floatIndices = [];
  36126. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  36127. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  36128. floatIndices.push(matricesIndex & 0x000000FF);
  36129. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  36130. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  36131. floatIndices.push(matricesIndex >> 24);
  36132. }
  36133. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  36134. }
  36135. else {
  36136. delete parsedGeometry.matricesIndices._isExpanded;
  36137. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  36138. }
  36139. }
  36140. if (parsedGeometry.matricesWeights) {
  36141. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  36142. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  36143. }
  36144. if (parsedGeometry.matricesWeightsExtra) {
  36145. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  36146. }
  36147. mesh.setIndices(parsedGeometry.indices, null);
  36148. }
  36149. // SubMeshes
  36150. if (parsedGeometry.subMeshes) {
  36151. mesh.subMeshes = [];
  36152. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  36153. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  36154. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  36155. }
  36156. }
  36157. // Flat shading
  36158. if (mesh._shouldGenerateFlatShading) {
  36159. mesh.convertToFlatShadedMesh();
  36160. delete mesh._shouldGenerateFlatShading;
  36161. }
  36162. // Update
  36163. mesh.computeWorldMatrix(true);
  36164. // Octree
  36165. var sceneOctree = scene.selectionOctree;
  36166. if (sceneOctree !== undefined && sceneOctree !== null) {
  36167. sceneOctree.addMesh(mesh);
  36168. }
  36169. };
  36170. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  36171. var epsilon = 1e-3;
  36172. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  36173. return;
  36174. }
  36175. var noInfluenceBoneIndex = 0.0;
  36176. if (parsedGeometry.skeletonId > -1) {
  36177. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  36178. if (!skeleton) {
  36179. return;
  36180. }
  36181. noInfluenceBoneIndex = skeleton.bones.length;
  36182. }
  36183. else {
  36184. return;
  36185. }
  36186. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  36187. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  36188. var matricesWeights = parsedGeometry.matricesWeights;
  36189. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  36190. var influencers = parsedGeometry.numBoneInfluencer;
  36191. var size = matricesWeights.length;
  36192. for (var i = 0; i < size; i += 4) {
  36193. var weight = 0.0;
  36194. var firstZeroWeight = -1;
  36195. for (var j = 0; j < 4; j++) {
  36196. var w = matricesWeights[i + j];
  36197. weight += w;
  36198. if (w < epsilon && firstZeroWeight < 0) {
  36199. firstZeroWeight = j;
  36200. }
  36201. }
  36202. if (matricesWeightsExtra) {
  36203. for (var j = 0; j < 4; j++) {
  36204. var w = matricesWeightsExtra[i + j];
  36205. weight += w;
  36206. if (w < epsilon && firstZeroWeight < 0) {
  36207. firstZeroWeight = j + 4;
  36208. }
  36209. }
  36210. }
  36211. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  36212. firstZeroWeight = influencers - 1;
  36213. }
  36214. if (weight > epsilon) {
  36215. var mweight = 1.0 / weight;
  36216. for (var j = 0; j < 4; j++) {
  36217. matricesWeights[i + j] *= mweight;
  36218. }
  36219. if (matricesWeightsExtra) {
  36220. for (var j = 0; j < 4; j++) {
  36221. matricesWeightsExtra[i + j] *= mweight;
  36222. }
  36223. }
  36224. }
  36225. else {
  36226. if (firstZeroWeight >= 4) {
  36227. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  36228. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  36229. }
  36230. else {
  36231. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  36232. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  36233. }
  36234. }
  36235. }
  36236. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  36237. if (parsedGeometry.matricesWeightsExtra) {
  36238. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  36239. }
  36240. };
  36241. /**
  36242. * Create a new geometry from persisted data (Using .babylon file format)
  36243. * @param parsedVertexData defines the persisted data
  36244. * @param scene defines the hosting scene
  36245. * @param rootUrl defines the root url to use to load assets (like delayed data)
  36246. * @returns the new geometry object
  36247. */
  36248. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  36249. if (scene.getGeometryByID(parsedVertexData.id)) {
  36250. return null; // null since geometry could be something else than a box...
  36251. }
  36252. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  36253. if (BABYLON.Tags) {
  36254. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  36255. }
  36256. if (parsedVertexData.delayLoadingFile) {
  36257. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  36258. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  36259. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  36260. geometry._delayInfo = [];
  36261. if (parsedVertexData.hasUVs) {
  36262. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  36263. }
  36264. if (parsedVertexData.hasUVs2) {
  36265. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  36266. }
  36267. if (parsedVertexData.hasUVs3) {
  36268. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  36269. }
  36270. if (parsedVertexData.hasUVs4) {
  36271. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  36272. }
  36273. if (parsedVertexData.hasUVs5) {
  36274. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  36275. }
  36276. if (parsedVertexData.hasUVs6) {
  36277. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  36278. }
  36279. if (parsedVertexData.hasColors) {
  36280. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  36281. }
  36282. if (parsedVertexData.hasMatricesIndices) {
  36283. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  36284. }
  36285. if (parsedVertexData.hasMatricesWeights) {
  36286. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  36287. }
  36288. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  36289. }
  36290. else {
  36291. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  36292. }
  36293. scene.pushGeometry(geometry, true);
  36294. return geometry;
  36295. };
  36296. return Geometry;
  36297. }());
  36298. BABYLON.Geometry = Geometry;
  36299. // Primitives
  36300. /// Abstract class
  36301. /**
  36302. * Abstract class used to provide common services for all typed geometries
  36303. */
  36304. var _PrimitiveGeometry = /** @class */ (function (_super) {
  36305. __extends(_PrimitiveGeometry, _super);
  36306. /**
  36307. * Creates a new typed geometry
  36308. * @param id defines the unique ID of the geometry
  36309. * @param scene defines the hosting scene
  36310. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36311. * @param mesh defines the hosting mesh (can be null)
  36312. */
  36313. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  36314. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  36315. if (mesh === void 0) { mesh = null; }
  36316. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  36317. _this._canBeRegenerated = _canBeRegenerated;
  36318. _this._beingRegenerated = true;
  36319. _this.regenerate();
  36320. _this._beingRegenerated = false;
  36321. return _this;
  36322. }
  36323. /**
  36324. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  36325. * @returns true if the geometry can be regenerated
  36326. */
  36327. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  36328. return this._canBeRegenerated;
  36329. };
  36330. /**
  36331. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  36332. */
  36333. _PrimitiveGeometry.prototype.regenerate = function () {
  36334. if (!this._canBeRegenerated) {
  36335. return;
  36336. }
  36337. this._beingRegenerated = true;
  36338. this.setAllVerticesData(this._regenerateVertexData(), false);
  36339. this._beingRegenerated = false;
  36340. };
  36341. /**
  36342. * Clone the geometry
  36343. * @param id defines the unique ID of the new geometry
  36344. * @returns the new geometry
  36345. */
  36346. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  36347. return _super.prototype.copy.call(this, id);
  36348. };
  36349. // overrides
  36350. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  36351. if (!this._beingRegenerated) {
  36352. return;
  36353. }
  36354. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  36355. };
  36356. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  36357. if (!this._beingRegenerated) {
  36358. return;
  36359. }
  36360. _super.prototype.setVerticesData.call(this, kind, data, false);
  36361. };
  36362. // to override
  36363. /** @ignore */
  36364. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  36365. throw new Error("Abstract method");
  36366. };
  36367. _PrimitiveGeometry.prototype.copy = function (id) {
  36368. throw new Error("Must be overriden in sub-classes.");
  36369. };
  36370. _PrimitiveGeometry.prototype.serialize = function () {
  36371. var serializationObject = _super.prototype.serialize.call(this);
  36372. serializationObject.canBeRegenerated = this.canBeRegenerated();
  36373. return serializationObject;
  36374. };
  36375. return _PrimitiveGeometry;
  36376. }(Geometry));
  36377. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  36378. /**
  36379. * Creates a ribbon geometry
  36380. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  36381. */
  36382. var RibbonGeometry = /** @class */ (function (_super) {
  36383. __extends(RibbonGeometry, _super);
  36384. /**
  36385. * Creates a ribbon geometry
  36386. * @param id defines the unique ID of the geometry
  36387. * @param scene defines the hosting scene
  36388. * @param pathArray defines the array of paths to use
  36389. * @param closeArray defines if the last path and the first path must be joined
  36390. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  36391. * @param offset defines the offset between points
  36392. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36393. * @param mesh defines the hosting mesh (can be null)
  36394. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36395. */
  36396. function RibbonGeometry(id, scene,
  36397. /**
  36398. * Defines the array of paths to use
  36399. */
  36400. pathArray,
  36401. /**
  36402. * Defines if the last and first points of each path in your pathArray must be joined
  36403. */
  36404. closeArray,
  36405. /**
  36406. * Defines if the last and first points of each path in your pathArray must be joined
  36407. */
  36408. closePath,
  36409. /**
  36410. * Defines the offset between points
  36411. */
  36412. offset, canBeRegenerated, mesh,
  36413. /**
  36414. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36415. */
  36416. side) {
  36417. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36418. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36419. _this.pathArray = pathArray;
  36420. _this.closeArray = closeArray;
  36421. _this.closePath = closePath;
  36422. _this.offset = offset;
  36423. _this.side = side;
  36424. return _this;
  36425. }
  36426. /** @ignore */
  36427. RibbonGeometry.prototype._regenerateVertexData = function () {
  36428. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  36429. };
  36430. RibbonGeometry.prototype.copy = function (id) {
  36431. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  36432. };
  36433. return RibbonGeometry;
  36434. }(_PrimitiveGeometry));
  36435. BABYLON.RibbonGeometry = RibbonGeometry;
  36436. /**
  36437. * Creates a box geometry
  36438. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  36439. */
  36440. var BoxGeometry = /** @class */ (function (_super) {
  36441. __extends(BoxGeometry, _super);
  36442. /**
  36443. * Creates a box geometry
  36444. * @param id defines the unique ID of the geometry
  36445. * @param scene defines the hosting scene
  36446. * @param size defines the zise of the box (width, height and depth are the same)
  36447. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36448. * @param mesh defines the hosting mesh (can be null)
  36449. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36450. */
  36451. function BoxGeometry(id, scene,
  36452. /**
  36453. * Defines the zise of the box (width, height and depth are the same)
  36454. */
  36455. size, canBeRegenerated, mesh,
  36456. /**
  36457. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36458. */
  36459. side) {
  36460. if (mesh === void 0) { mesh = null; }
  36461. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36462. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36463. _this.size = size;
  36464. _this.side = side;
  36465. return _this;
  36466. }
  36467. BoxGeometry.prototype._regenerateVertexData = function () {
  36468. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  36469. };
  36470. BoxGeometry.prototype.copy = function (id) {
  36471. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  36472. };
  36473. BoxGeometry.prototype.serialize = function () {
  36474. var serializationObject = _super.prototype.serialize.call(this);
  36475. serializationObject.size = this.size;
  36476. return serializationObject;
  36477. };
  36478. BoxGeometry.Parse = function (parsedBox, scene) {
  36479. if (scene.getGeometryByID(parsedBox.id)) {
  36480. return null; // null since geometry could be something else than a box...
  36481. }
  36482. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  36483. if (BABYLON.Tags) {
  36484. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  36485. }
  36486. scene.pushGeometry(box, true);
  36487. return box;
  36488. };
  36489. return BoxGeometry;
  36490. }(_PrimitiveGeometry));
  36491. BABYLON.BoxGeometry = BoxGeometry;
  36492. /**
  36493. * Creates a sphere geometry
  36494. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  36495. */
  36496. var SphereGeometry = /** @class */ (function (_super) {
  36497. __extends(SphereGeometry, _super);
  36498. /**
  36499. * Create a new sphere geometry
  36500. * @param id defines the unique ID of the geometry
  36501. * @param scene defines the hosting scene
  36502. * @param segments defines the number of segments to use to create the sphere
  36503. * @param diameter defines the diameter of the sphere
  36504. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36505. * @param mesh defines the hosting mesh (can be null)
  36506. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36507. */
  36508. function SphereGeometry(id, scene,
  36509. /**
  36510. * Defines the number of segments to use to create the sphere
  36511. */
  36512. segments,
  36513. /**
  36514. * Defines the diameter of the sphere
  36515. */
  36516. diameter, canBeRegenerated, mesh,
  36517. /**
  36518. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36519. */
  36520. side) {
  36521. if (mesh === void 0) { mesh = null; }
  36522. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36523. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36524. _this.segments = segments;
  36525. _this.diameter = diameter;
  36526. _this.side = side;
  36527. return _this;
  36528. }
  36529. SphereGeometry.prototype._regenerateVertexData = function () {
  36530. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  36531. };
  36532. SphereGeometry.prototype.copy = function (id) {
  36533. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  36534. };
  36535. SphereGeometry.prototype.serialize = function () {
  36536. var serializationObject = _super.prototype.serialize.call(this);
  36537. serializationObject.segments = this.segments;
  36538. serializationObject.diameter = this.diameter;
  36539. return serializationObject;
  36540. };
  36541. SphereGeometry.Parse = function (parsedSphere, scene) {
  36542. if (scene.getGeometryByID(parsedSphere.id)) {
  36543. return null; // null since geometry could be something else than a sphere...
  36544. }
  36545. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  36546. if (BABYLON.Tags) {
  36547. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  36548. }
  36549. scene.pushGeometry(sphere, true);
  36550. return sphere;
  36551. };
  36552. return SphereGeometry;
  36553. }(_PrimitiveGeometry));
  36554. BABYLON.SphereGeometry = SphereGeometry;
  36555. /**
  36556. * Creates a disc geometry
  36557. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  36558. */
  36559. var DiscGeometry = /** @class */ (function (_super) {
  36560. __extends(DiscGeometry, _super);
  36561. /**
  36562. * Creates a new disc geometry
  36563. * @param id defines the unique ID of the geometry
  36564. * @param scene defines the hosting scene
  36565. * @param radius defines the radius of the disc
  36566. * @param tessellation defines the tesselation factor to apply to the disc
  36567. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36568. * @param mesh defines the hosting mesh (can be null)
  36569. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36570. */
  36571. function DiscGeometry(id, scene,
  36572. /**
  36573. * Defines the radius of the disc
  36574. */
  36575. radius,
  36576. /**
  36577. * Defines the tesselation factor to apply to the disc
  36578. */
  36579. tessellation, canBeRegenerated, mesh,
  36580. /**
  36581. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36582. */
  36583. side) {
  36584. if (mesh === void 0) { mesh = null; }
  36585. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36586. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36587. _this.radius = radius;
  36588. _this.tessellation = tessellation;
  36589. _this.side = side;
  36590. return _this;
  36591. }
  36592. DiscGeometry.prototype._regenerateVertexData = function () {
  36593. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  36594. };
  36595. DiscGeometry.prototype.copy = function (id) {
  36596. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  36597. };
  36598. return DiscGeometry;
  36599. }(_PrimitiveGeometry));
  36600. BABYLON.DiscGeometry = DiscGeometry;
  36601. /**
  36602. * Creates a new cylinder geometry
  36603. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  36604. */
  36605. var CylinderGeometry = /** @class */ (function (_super) {
  36606. __extends(CylinderGeometry, _super);
  36607. /**
  36608. * Creates a new cylinder geometry
  36609. * @param id defines the unique ID of the geometry
  36610. * @param scene defines the hosting scene
  36611. * @param height defines the height of the cylinder
  36612. * @param diameterTop defines the diameter of the cylinder's top cap
  36613. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  36614. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  36615. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  36616. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36617. * @param mesh defines the hosting mesh (can be null)
  36618. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36619. */
  36620. function CylinderGeometry(id, scene,
  36621. /**
  36622. * Defines the height of the cylinder
  36623. */
  36624. height,
  36625. /**
  36626. * Defines the diameter of the cylinder's top cap
  36627. */
  36628. diameterTop,
  36629. /**
  36630. * Defines the diameter of the cylinder's bottom cap
  36631. */
  36632. diameterBottom,
  36633. /**
  36634. * Defines the tessellation factor to apply to the cylinder
  36635. */
  36636. tessellation,
  36637. /**
  36638. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  36639. */
  36640. subdivisions, canBeRegenerated, mesh,
  36641. /**
  36642. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36643. */
  36644. side) {
  36645. if (subdivisions === void 0) { subdivisions = 1; }
  36646. if (mesh === void 0) { mesh = null; }
  36647. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36648. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36649. _this.height = height;
  36650. _this.diameterTop = diameterTop;
  36651. _this.diameterBottom = diameterBottom;
  36652. _this.tessellation = tessellation;
  36653. _this.subdivisions = subdivisions;
  36654. _this.side = side;
  36655. return _this;
  36656. }
  36657. CylinderGeometry.prototype._regenerateVertexData = function () {
  36658. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  36659. };
  36660. CylinderGeometry.prototype.copy = function (id) {
  36661. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  36662. };
  36663. CylinderGeometry.prototype.serialize = function () {
  36664. var serializationObject = _super.prototype.serialize.call(this);
  36665. serializationObject.height = this.height;
  36666. serializationObject.diameterTop = this.diameterTop;
  36667. serializationObject.diameterBottom = this.diameterBottom;
  36668. serializationObject.tessellation = this.tessellation;
  36669. return serializationObject;
  36670. };
  36671. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  36672. if (scene.getGeometryByID(parsedCylinder.id)) {
  36673. return null; // null since geometry could be something else than a cylinder...
  36674. }
  36675. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  36676. if (BABYLON.Tags) {
  36677. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  36678. }
  36679. scene.pushGeometry(cylinder, true);
  36680. return cylinder;
  36681. };
  36682. return CylinderGeometry;
  36683. }(_PrimitiveGeometry));
  36684. BABYLON.CylinderGeometry = CylinderGeometry;
  36685. /**
  36686. * Creates a new torus geometry
  36687. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  36688. */
  36689. var TorusGeometry = /** @class */ (function (_super) {
  36690. __extends(TorusGeometry, _super);
  36691. /**
  36692. * Creates a new torus geometry
  36693. * @param id defines the unique ID of the geometry
  36694. * @param scene defines the hosting scene
  36695. * @param diameter defines the diameter of the torus
  36696. * @param thickness defines the thickness of the torus (ie. internal diameter)
  36697. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  36698. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36699. * @param mesh defines the hosting mesh (can be null)
  36700. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36701. */
  36702. function TorusGeometry(id, scene,
  36703. /**
  36704. * Defines the diameter of the torus
  36705. */
  36706. diameter,
  36707. /**
  36708. * Defines the thickness of the torus (ie. internal diameter)
  36709. */
  36710. thickness,
  36711. /**
  36712. * Defines the tesselation factor to apply to the torus
  36713. */
  36714. tessellation, canBeRegenerated, mesh,
  36715. /**
  36716. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36717. */
  36718. side) {
  36719. if (mesh === void 0) { mesh = null; }
  36720. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36721. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36722. _this.diameter = diameter;
  36723. _this.thickness = thickness;
  36724. _this.tessellation = tessellation;
  36725. _this.side = side;
  36726. return _this;
  36727. }
  36728. TorusGeometry.prototype._regenerateVertexData = function () {
  36729. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  36730. };
  36731. TorusGeometry.prototype.copy = function (id) {
  36732. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  36733. };
  36734. TorusGeometry.prototype.serialize = function () {
  36735. var serializationObject = _super.prototype.serialize.call(this);
  36736. serializationObject.diameter = this.diameter;
  36737. serializationObject.thickness = this.thickness;
  36738. serializationObject.tessellation = this.tessellation;
  36739. return serializationObject;
  36740. };
  36741. TorusGeometry.Parse = function (parsedTorus, scene) {
  36742. if (scene.getGeometryByID(parsedTorus.id)) {
  36743. return null; // null since geometry could be something else than a torus...
  36744. }
  36745. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  36746. if (BABYLON.Tags) {
  36747. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  36748. }
  36749. scene.pushGeometry(torus, true);
  36750. return torus;
  36751. };
  36752. return TorusGeometry;
  36753. }(_PrimitiveGeometry));
  36754. BABYLON.TorusGeometry = TorusGeometry;
  36755. /**
  36756. * Creates a new ground geometry
  36757. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  36758. */
  36759. var GroundGeometry = /** @class */ (function (_super) {
  36760. __extends(GroundGeometry, _super);
  36761. /**
  36762. * Creates a new ground geometry
  36763. * @param id defines the unique ID of the geometry
  36764. * @param scene defines the hosting scene
  36765. * @param width defines the width of the ground
  36766. * @param height defines the height of the ground
  36767. * @param subdivisions defines the subdivisions to apply to the ground
  36768. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36769. * @param mesh defines the hosting mesh (can be null)
  36770. */
  36771. function GroundGeometry(id, scene,
  36772. /**
  36773. * Defines the width of the ground
  36774. */
  36775. width,
  36776. /**
  36777. * Defines the height of the ground
  36778. */
  36779. height,
  36780. /**
  36781. * Defines the subdivisions to apply to the ground
  36782. */
  36783. subdivisions, canBeRegenerated, mesh) {
  36784. if (mesh === void 0) { mesh = null; }
  36785. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36786. _this.width = width;
  36787. _this.height = height;
  36788. _this.subdivisions = subdivisions;
  36789. return _this;
  36790. }
  36791. GroundGeometry.prototype._regenerateVertexData = function () {
  36792. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  36793. };
  36794. GroundGeometry.prototype.copy = function (id) {
  36795. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  36796. };
  36797. GroundGeometry.prototype.serialize = function () {
  36798. var serializationObject = _super.prototype.serialize.call(this);
  36799. serializationObject.width = this.width;
  36800. serializationObject.height = this.height;
  36801. serializationObject.subdivisions = this.subdivisions;
  36802. return serializationObject;
  36803. };
  36804. GroundGeometry.Parse = function (parsedGround, scene) {
  36805. if (scene.getGeometryByID(parsedGround.id)) {
  36806. return null; // null since geometry could be something else than a ground...
  36807. }
  36808. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  36809. if (BABYLON.Tags) {
  36810. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  36811. }
  36812. scene.pushGeometry(ground, true);
  36813. return ground;
  36814. };
  36815. return GroundGeometry;
  36816. }(_PrimitiveGeometry));
  36817. BABYLON.GroundGeometry = GroundGeometry;
  36818. /**
  36819. * Creates a tiled ground geometry
  36820. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  36821. */
  36822. var TiledGroundGeometry = /** @class */ (function (_super) {
  36823. __extends(TiledGroundGeometry, _super);
  36824. /**
  36825. * Creates a tiled ground geometry
  36826. * @param id defines the unique ID of the geometry
  36827. * @param scene defines the hosting scene
  36828. * @param xmin defines the minimum value on X axis
  36829. * @param zmin defines the minimum value on Z axis
  36830. * @param xmax defines the maximum value on X axis
  36831. * @param zmax defines the maximum value on Z axis
  36832. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  36833. * @param precision defines the precision to use when computing the tiles
  36834. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36835. * @param mesh defines the hosting mesh (can be null)
  36836. */
  36837. function TiledGroundGeometry(id, scene,
  36838. /**
  36839. * Defines the minimum value on X axis
  36840. */
  36841. xmin,
  36842. /**
  36843. * Defines the minimum value on Z axis
  36844. */
  36845. zmin,
  36846. /**
  36847. * Defines the maximum value on X axis
  36848. */
  36849. xmax,
  36850. /**
  36851. * Defines the maximum value on Z axis
  36852. */
  36853. zmax,
  36854. /**
  36855. * Defines the subdivisions to apply to the ground
  36856. */
  36857. subdivisions,
  36858. /**
  36859. * Defines the precision to use when computing the tiles
  36860. */
  36861. precision, canBeRegenerated, mesh) {
  36862. if (mesh === void 0) { mesh = null; }
  36863. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36864. _this.xmin = xmin;
  36865. _this.zmin = zmin;
  36866. _this.xmax = xmax;
  36867. _this.zmax = zmax;
  36868. _this.subdivisions = subdivisions;
  36869. _this.precision = precision;
  36870. return _this;
  36871. }
  36872. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  36873. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  36874. };
  36875. TiledGroundGeometry.prototype.copy = function (id) {
  36876. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  36877. };
  36878. return TiledGroundGeometry;
  36879. }(_PrimitiveGeometry));
  36880. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  36881. /**
  36882. * Creates a plane geometry
  36883. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  36884. */
  36885. var PlaneGeometry = /** @class */ (function (_super) {
  36886. __extends(PlaneGeometry, _super);
  36887. /**
  36888. * Creates a plane geometry
  36889. * @param id defines the unique ID of the geometry
  36890. * @param scene defines the hosting scene
  36891. * @param size defines the size of the plane (width === height)
  36892. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36893. * @param mesh defines the hosting mesh (can be null)
  36894. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36895. */
  36896. function PlaneGeometry(id, scene,
  36897. /**
  36898. * Defines the size of the plane (width === height)
  36899. */
  36900. size, canBeRegenerated, mesh,
  36901. /**
  36902. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36903. */
  36904. side) {
  36905. if (mesh === void 0) { mesh = null; }
  36906. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36907. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36908. _this.size = size;
  36909. _this.side = side;
  36910. return _this;
  36911. }
  36912. PlaneGeometry.prototype._regenerateVertexData = function () {
  36913. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  36914. };
  36915. PlaneGeometry.prototype.copy = function (id) {
  36916. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  36917. };
  36918. PlaneGeometry.prototype.serialize = function () {
  36919. var serializationObject = _super.prototype.serialize.call(this);
  36920. serializationObject.size = this.size;
  36921. return serializationObject;
  36922. };
  36923. PlaneGeometry.Parse = function (parsedPlane, scene) {
  36924. if (scene.getGeometryByID(parsedPlane.id)) {
  36925. return null; // null since geometry could be something else than a ground...
  36926. }
  36927. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  36928. if (BABYLON.Tags) {
  36929. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  36930. }
  36931. scene.pushGeometry(plane, true);
  36932. return plane;
  36933. };
  36934. return PlaneGeometry;
  36935. }(_PrimitiveGeometry));
  36936. BABYLON.PlaneGeometry = PlaneGeometry;
  36937. /**
  36938. * Creates a torus knot geometry
  36939. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  36940. */
  36941. var TorusKnotGeometry = /** @class */ (function (_super) {
  36942. __extends(TorusKnotGeometry, _super);
  36943. /**
  36944. * Creates a torus knot geometry
  36945. * @param id defines the unique ID of the geometry
  36946. * @param scene defines the hosting scene
  36947. * @param radius defines the radius of the torus knot
  36948. * @param tube defines the thickness of the torus knot tube
  36949. * @param radialSegments defines the number of radial segments
  36950. * @param tubularSegments defines the number of tubular segments
  36951. * @param p defines the first number of windings
  36952. * @param q defines the second number of windings
  36953. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  36954. * @param mesh defines the hosting mesh (can be null)
  36955. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36956. */
  36957. function TorusKnotGeometry(id, scene,
  36958. /**
  36959. * Defines the radius of the torus knot
  36960. */
  36961. radius,
  36962. /**
  36963. * Defines the thickness of the torus knot tube
  36964. */
  36965. tube,
  36966. /**
  36967. * Defines the number of radial segments
  36968. */
  36969. radialSegments,
  36970. /**
  36971. * Defines the number of tubular segments
  36972. */
  36973. tubularSegments,
  36974. /**
  36975. * Defines the first number of windings
  36976. */
  36977. p,
  36978. /**
  36979. * Defines the second number of windings
  36980. */
  36981. q, canBeRegenerated, mesh,
  36982. /**
  36983. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  36984. */
  36985. side) {
  36986. if (mesh === void 0) { mesh = null; }
  36987. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36988. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36989. _this.radius = radius;
  36990. _this.tube = tube;
  36991. _this.radialSegments = radialSegments;
  36992. _this.tubularSegments = tubularSegments;
  36993. _this.p = p;
  36994. _this.q = q;
  36995. _this.side = side;
  36996. return _this;
  36997. }
  36998. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  36999. 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 });
  37000. };
  37001. TorusKnotGeometry.prototype.copy = function (id) {
  37002. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  37003. };
  37004. TorusKnotGeometry.prototype.serialize = function () {
  37005. var serializationObject = _super.prototype.serialize.call(this);
  37006. serializationObject.radius = this.radius;
  37007. serializationObject.tube = this.tube;
  37008. serializationObject.radialSegments = this.radialSegments;
  37009. serializationObject.tubularSegments = this.tubularSegments;
  37010. serializationObject.p = this.p;
  37011. serializationObject.q = this.q;
  37012. return serializationObject;
  37013. };
  37014. ;
  37015. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  37016. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  37017. return null; // null since geometry could be something else than a ground...
  37018. }
  37019. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  37020. if (BABYLON.Tags) {
  37021. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  37022. }
  37023. scene.pushGeometry(torusKnot, true);
  37024. return torusKnot;
  37025. };
  37026. return TorusKnotGeometry;
  37027. }(_PrimitiveGeometry));
  37028. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  37029. //}
  37030. })(BABYLON || (BABYLON = {}));
  37031. //# sourceMappingURL=babylon.geometry.js.map
  37032. "use strict";
  37033. var BABYLON;
  37034. (function (BABYLON) {
  37035. /**
  37036. * PostProcessManager is used to manage one or more post processes or post process pipelines
  37037. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  37038. */
  37039. var PostProcessManager = /** @class */ (function () {
  37040. /**
  37041. * Creates a new instance of @see PostProcess
  37042. * @param scene The scene that the post process is associated with.
  37043. */
  37044. function PostProcessManager(scene) {
  37045. this._vertexBuffers = {};
  37046. this._scene = scene;
  37047. }
  37048. PostProcessManager.prototype._prepareBuffers = function () {
  37049. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  37050. return;
  37051. }
  37052. // VBO
  37053. var vertices = [];
  37054. vertices.push(1, 1);
  37055. vertices.push(-1, 1);
  37056. vertices.push(-1, -1);
  37057. vertices.push(1, -1);
  37058. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  37059. this._buildIndexBuffer();
  37060. };
  37061. PostProcessManager.prototype._buildIndexBuffer = function () {
  37062. // Indices
  37063. var indices = [];
  37064. indices.push(0);
  37065. indices.push(1);
  37066. indices.push(2);
  37067. indices.push(0);
  37068. indices.push(2);
  37069. indices.push(3);
  37070. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  37071. };
  37072. /**
  37073. * Rebuilds the vertex buffers of the manager.
  37074. */
  37075. PostProcessManager.prototype._rebuild = function () {
  37076. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  37077. if (!vb) {
  37078. return;
  37079. }
  37080. vb._rebuild();
  37081. this._buildIndexBuffer();
  37082. };
  37083. // Methods
  37084. /**
  37085. * Prepares a frame to be run through a post process.
  37086. * @param sourceTexture The input texture to the post procesess. (default: null)
  37087. * @param postProcesses An array of post processes to be run. (default: null)
  37088. * @returns True if the post processes were able to be run.
  37089. */
  37090. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  37091. if (sourceTexture === void 0) { sourceTexture = null; }
  37092. if (postProcesses === void 0) { postProcesses = null; }
  37093. var camera = this._scene.activeCamera;
  37094. if (!camera) {
  37095. return false;
  37096. }
  37097. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  37098. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  37099. return false;
  37100. }
  37101. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  37102. return true;
  37103. };
  37104. /**
  37105. * Manually render a set of post processes to a texture.
  37106. * @param postProcesses An array of post processes to be run.
  37107. * @param targetTexture The target texture to render to.
  37108. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  37109. */
  37110. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  37111. if (targetTexture === void 0) { targetTexture = null; }
  37112. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  37113. var engine = this._scene.getEngine();
  37114. for (var index = 0; index < postProcesses.length; index++) {
  37115. if (index < postProcesses.length - 1) {
  37116. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  37117. }
  37118. else {
  37119. if (targetTexture) {
  37120. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  37121. }
  37122. else {
  37123. engine.restoreDefaultFramebuffer();
  37124. }
  37125. }
  37126. var pp = postProcesses[index];
  37127. var effect = pp.apply();
  37128. if (effect) {
  37129. pp.onBeforeRenderObservable.notifyObservers(effect);
  37130. // VBOs
  37131. this._prepareBuffers();
  37132. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  37133. // Draw order
  37134. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  37135. pp.onAfterRenderObservable.notifyObservers(effect);
  37136. }
  37137. }
  37138. // Restore depth buffer
  37139. engine.setDepthBuffer(true);
  37140. engine.setDepthWrite(true);
  37141. };
  37142. /**
  37143. * Finalize the result of the output of the postprocesses.
  37144. * @param doNotPresent If true the result will not be displayed to the screen.
  37145. * @param targetTexture The target texture to render to.
  37146. * @param faceIndex The index of the face to bind the target texture to.
  37147. * @param postProcesses The array of post processes to render.
  37148. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  37149. */
  37150. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  37151. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  37152. var camera = this._scene.activeCamera;
  37153. if (!camera) {
  37154. return;
  37155. }
  37156. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  37157. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  37158. return;
  37159. }
  37160. var engine = this._scene.getEngine();
  37161. for (var index = 0, len = postProcesses.length; index < len; index++) {
  37162. var pp = postProcesses[index];
  37163. if (index < len - 1) {
  37164. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  37165. }
  37166. else {
  37167. if (targetTexture) {
  37168. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  37169. }
  37170. else {
  37171. engine.restoreDefaultFramebuffer();
  37172. }
  37173. }
  37174. if (doNotPresent) {
  37175. break;
  37176. }
  37177. var effect = pp.apply();
  37178. if (effect) {
  37179. pp.onBeforeRenderObservable.notifyObservers(effect);
  37180. // VBOs
  37181. this._prepareBuffers();
  37182. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  37183. // Draw order
  37184. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  37185. pp.onAfterRenderObservable.notifyObservers(effect);
  37186. }
  37187. }
  37188. // Restore states
  37189. engine.setDepthBuffer(true);
  37190. engine.setDepthWrite(true);
  37191. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  37192. };
  37193. /**
  37194. * Disposes of the post process manager.
  37195. */
  37196. PostProcessManager.prototype.dispose = function () {
  37197. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  37198. if (buffer) {
  37199. buffer.dispose();
  37200. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  37201. }
  37202. if (this._indexBuffer) {
  37203. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  37204. this._indexBuffer = null;
  37205. }
  37206. };
  37207. return PostProcessManager;
  37208. }());
  37209. BABYLON.PostProcessManager = PostProcessManager;
  37210. })(BABYLON || (BABYLON = {}));
  37211. //# sourceMappingURL=babylon.postProcessManager.js.map
  37212. "use strict";
  37213. var BABYLON;
  37214. (function (BABYLON) {
  37215. /**
  37216. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  37217. */
  37218. var PerformanceMonitor = /** @class */ (function () {
  37219. /**
  37220. * constructor
  37221. * @param frameSampleSize The number of samples required to saturate the sliding window
  37222. */
  37223. function PerformanceMonitor(frameSampleSize) {
  37224. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  37225. this._enabled = true;
  37226. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  37227. }
  37228. /**
  37229. * Samples current frame
  37230. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  37231. */
  37232. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  37233. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  37234. if (!this._enabled)
  37235. return;
  37236. if (this._lastFrameTimeMs != null) {
  37237. var dt = timeMs - this._lastFrameTimeMs;
  37238. this._rollingFrameTime.add(dt);
  37239. }
  37240. this._lastFrameTimeMs = timeMs;
  37241. };
  37242. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  37243. /**
  37244. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  37245. * @return Average frame time in milliseconds
  37246. */
  37247. get: function () {
  37248. return this._rollingFrameTime.average;
  37249. },
  37250. enumerable: true,
  37251. configurable: true
  37252. });
  37253. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  37254. /**
  37255. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  37256. * @return Frame time variance in milliseconds squared
  37257. */
  37258. get: function () {
  37259. return this._rollingFrameTime.variance;
  37260. },
  37261. enumerable: true,
  37262. configurable: true
  37263. });
  37264. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  37265. /**
  37266. * Returns the frame time of the most recent frame
  37267. * @return Frame time in milliseconds
  37268. */
  37269. get: function () {
  37270. return this._rollingFrameTime.history(0);
  37271. },
  37272. enumerable: true,
  37273. configurable: true
  37274. });
  37275. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  37276. /**
  37277. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  37278. * @return Framerate in frames per second
  37279. */
  37280. get: function () {
  37281. return 1000.0 / this._rollingFrameTime.average;
  37282. },
  37283. enumerable: true,
  37284. configurable: true
  37285. });
  37286. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  37287. /**
  37288. * Returns the average framerate in frames per second using the most recent frame time
  37289. * @return Framerate in frames per second
  37290. */
  37291. get: function () {
  37292. var history = this._rollingFrameTime.history(0);
  37293. if (history === 0) {
  37294. return 0;
  37295. }
  37296. return 1000.0 / history;
  37297. },
  37298. enumerable: true,
  37299. configurable: true
  37300. });
  37301. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  37302. /**
  37303. * Returns true if enough samples have been taken to completely fill the sliding window
  37304. * @return true if saturated
  37305. */
  37306. get: function () {
  37307. return this._rollingFrameTime.isSaturated();
  37308. },
  37309. enumerable: true,
  37310. configurable: true
  37311. });
  37312. /**
  37313. * Enables contributions to the sliding window sample set
  37314. */
  37315. PerformanceMonitor.prototype.enable = function () {
  37316. this._enabled = true;
  37317. };
  37318. /**
  37319. * Disables contributions to the sliding window sample set
  37320. * Samples will not be interpolated over the disabled period
  37321. */
  37322. PerformanceMonitor.prototype.disable = function () {
  37323. this._enabled = false;
  37324. //clear last sample to avoid interpolating over the disabled period when next enabled
  37325. this._lastFrameTimeMs = null;
  37326. };
  37327. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  37328. /**
  37329. * Returns true if sampling is enabled
  37330. * @return true if enabled
  37331. */
  37332. get: function () {
  37333. return this._enabled;
  37334. },
  37335. enumerable: true,
  37336. configurable: true
  37337. });
  37338. /**
  37339. * Resets performance monitor
  37340. */
  37341. PerformanceMonitor.prototype.reset = function () {
  37342. //clear last sample to avoid interpolating over the disabled period when next enabled
  37343. this._lastFrameTimeMs = null;
  37344. //wipe record
  37345. this._rollingFrameTime.reset();
  37346. };
  37347. return PerformanceMonitor;
  37348. }());
  37349. BABYLON.PerformanceMonitor = PerformanceMonitor;
  37350. /**
  37351. * RollingAverage
  37352. *
  37353. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  37354. */
  37355. var RollingAverage = /** @class */ (function () {
  37356. /**
  37357. * constructor
  37358. * @param length The number of samples required to saturate the sliding window
  37359. */
  37360. function RollingAverage(length) {
  37361. this._samples = new Array(length);
  37362. this.reset();
  37363. }
  37364. /**
  37365. * Adds a sample to the sample set
  37366. * @param v The sample value
  37367. */
  37368. RollingAverage.prototype.add = function (v) {
  37369. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  37370. var delta;
  37371. //we need to check if we've already wrapped round
  37372. if (this.isSaturated()) {
  37373. //remove bottom of stack from mean
  37374. var bottomValue = this._samples[this._pos];
  37375. delta = bottomValue - this.average;
  37376. this.average -= delta / (this._sampleCount - 1);
  37377. this._m2 -= delta * (bottomValue - this.average);
  37378. }
  37379. else {
  37380. this._sampleCount++;
  37381. }
  37382. //add new value to mean
  37383. delta = v - this.average;
  37384. this.average += delta / (this._sampleCount);
  37385. this._m2 += delta * (v - this.average);
  37386. //set the new variance
  37387. this.variance = this._m2 / (this._sampleCount - 1);
  37388. this._samples[this._pos] = v;
  37389. this._pos++;
  37390. this._pos %= this._samples.length; //positive wrap around
  37391. };
  37392. /**
  37393. * Returns previously added values or null if outside of history or outside the sliding window domain
  37394. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  37395. * @return Value previously recorded with add() or null if outside of range
  37396. */
  37397. RollingAverage.prototype.history = function (i) {
  37398. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  37399. return 0;
  37400. }
  37401. var i0 = this._wrapPosition(this._pos - 1.0);
  37402. return this._samples[this._wrapPosition(i0 - i)];
  37403. };
  37404. /**
  37405. * Returns true if enough samples have been taken to completely fill the sliding window
  37406. * @return true if sample-set saturated
  37407. */
  37408. RollingAverage.prototype.isSaturated = function () {
  37409. return this._sampleCount >= this._samples.length;
  37410. };
  37411. /**
  37412. * Resets the rolling average (equivalent to 0 samples taken so far)
  37413. */
  37414. RollingAverage.prototype.reset = function () {
  37415. this.average = 0;
  37416. this.variance = 0;
  37417. this._sampleCount = 0;
  37418. this._pos = 0;
  37419. this._m2 = 0;
  37420. };
  37421. /**
  37422. * Wraps a value around the sample range boundaries
  37423. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  37424. * @return Wrapped position in sample range
  37425. */
  37426. RollingAverage.prototype._wrapPosition = function (i) {
  37427. var max = this._samples.length;
  37428. return ((i % max) + max) % max;
  37429. };
  37430. return RollingAverage;
  37431. }());
  37432. BABYLON.RollingAverage = RollingAverage;
  37433. })(BABYLON || (BABYLON = {}));
  37434. //# sourceMappingURL=babylon.performanceMonitor.js.map
  37435. "use strict";
  37436. var BABYLON;
  37437. (function (BABYLON) {
  37438. /**
  37439. * This groups together the common properties used for image processing either in direct forward pass
  37440. * or through post processing effect depending on the use of the image processing pipeline in your scene
  37441. * or not.
  37442. */
  37443. var ImageProcessingConfiguration = /** @class */ (function () {
  37444. function ImageProcessingConfiguration() {
  37445. /**
  37446. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  37447. */
  37448. this.colorCurves = new BABYLON.ColorCurves();
  37449. this._colorCurvesEnabled = false;
  37450. this._colorGradingEnabled = false;
  37451. this._colorGradingWithGreenDepth = true;
  37452. this._colorGradingBGR = true;
  37453. this._exposure = 1.0;
  37454. this._toneMappingEnabled = false;
  37455. this._contrast = 1.0;
  37456. /**
  37457. * Vignette stretch size.
  37458. */
  37459. this.vignetteStretch = 0;
  37460. /**
  37461. * Vignette centre X Offset.
  37462. */
  37463. this.vignetteCentreX = 0;
  37464. /**
  37465. * Vignette centre Y Offset.
  37466. */
  37467. this.vignetteCentreY = 0;
  37468. /**
  37469. * Vignette weight or intensity of the vignette effect.
  37470. */
  37471. this.vignetteWeight = 1.5;
  37472. /**
  37473. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  37474. * if vignetteEnabled is set to true.
  37475. */
  37476. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  37477. /**
  37478. * Camera field of view used by the Vignette effect.
  37479. */
  37480. this.vignetteCameraFov = 0.5;
  37481. this._grainEnabled = false;
  37482. this._grainIntensity = 30;
  37483. this._grainAnimated = false;
  37484. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  37485. this._vignetteEnabled = false;
  37486. this._applyByPostProcess = false;
  37487. this._isEnabled = true;
  37488. /**
  37489. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  37490. * @type {BABYLON.Observable}
  37491. */
  37492. this.onUpdateParameters = new BABYLON.Observable();
  37493. }
  37494. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  37495. /**
  37496. * Gets wether the color curves effect is enabled.
  37497. */
  37498. get: function () {
  37499. return this._colorCurvesEnabled;
  37500. },
  37501. /**
  37502. * Sets wether the color curves effect is enabled.
  37503. */
  37504. set: function (value) {
  37505. if (this._colorCurvesEnabled === value) {
  37506. return;
  37507. }
  37508. this._colorCurvesEnabled = value;
  37509. this._updateParameters();
  37510. },
  37511. enumerable: true,
  37512. configurable: true
  37513. });
  37514. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  37515. /**
  37516. * Gets wether the color grading effect is enabled.
  37517. */
  37518. get: function () {
  37519. return this._colorGradingEnabled;
  37520. },
  37521. /**
  37522. * Sets wether the color grading effect is enabled.
  37523. */
  37524. set: function (value) {
  37525. if (this._colorGradingEnabled === value) {
  37526. return;
  37527. }
  37528. this._colorGradingEnabled = value;
  37529. this._updateParameters();
  37530. },
  37531. enumerable: true,
  37532. configurable: true
  37533. });
  37534. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  37535. /**
  37536. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  37537. */
  37538. get: function () {
  37539. return this._colorGradingWithGreenDepth;
  37540. },
  37541. /**
  37542. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  37543. */
  37544. set: function (value) {
  37545. if (this._colorGradingWithGreenDepth === value) {
  37546. return;
  37547. }
  37548. this._colorGradingWithGreenDepth = value;
  37549. this._updateParameters();
  37550. },
  37551. enumerable: true,
  37552. configurable: true
  37553. });
  37554. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  37555. /**
  37556. * Gets wether the color grading texture contains BGR values.
  37557. */
  37558. get: function () {
  37559. return this._colorGradingBGR;
  37560. },
  37561. /**
  37562. * Sets wether the color grading texture contains BGR values.
  37563. */
  37564. set: function (value) {
  37565. if (this._colorGradingBGR === value) {
  37566. return;
  37567. }
  37568. this._colorGradingBGR = value;
  37569. this._updateParameters();
  37570. },
  37571. enumerable: true,
  37572. configurable: true
  37573. });
  37574. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  37575. /**
  37576. * Gets the Exposure used in the effect.
  37577. */
  37578. get: function () {
  37579. return this._exposure;
  37580. },
  37581. /**
  37582. * Sets the Exposure used in the effect.
  37583. */
  37584. set: function (value) {
  37585. if (this._exposure === value) {
  37586. return;
  37587. }
  37588. this._exposure = value;
  37589. this._updateParameters();
  37590. },
  37591. enumerable: true,
  37592. configurable: true
  37593. });
  37594. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  37595. /**
  37596. * Gets wether the tone mapping effect is enabled.
  37597. */
  37598. get: function () {
  37599. return this._toneMappingEnabled;
  37600. },
  37601. /**
  37602. * Sets wether the tone mapping effect is enabled.
  37603. */
  37604. set: function (value) {
  37605. if (this._toneMappingEnabled === value) {
  37606. return;
  37607. }
  37608. this._toneMappingEnabled = value;
  37609. this._updateParameters();
  37610. },
  37611. enumerable: true,
  37612. configurable: true
  37613. });
  37614. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  37615. /**
  37616. * Gets the contrast used in the effect.
  37617. */
  37618. get: function () {
  37619. return this._contrast;
  37620. },
  37621. /**
  37622. * Sets the contrast used in the effect.
  37623. */
  37624. set: function (value) {
  37625. if (this._contrast === value) {
  37626. return;
  37627. }
  37628. this._contrast = value;
  37629. this._updateParameters();
  37630. },
  37631. enumerable: true,
  37632. configurable: true
  37633. });
  37634. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainEnabled", {
  37635. /**
  37636. * If the grain effect should be enabled.
  37637. */
  37638. get: function () {
  37639. return this._grainEnabled;
  37640. },
  37641. set: function (value) {
  37642. if (this._grainEnabled === value) {
  37643. return;
  37644. }
  37645. this._grainEnabled = value;
  37646. this._updateParameters();
  37647. },
  37648. enumerable: true,
  37649. configurable: true
  37650. });
  37651. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainIntensity", {
  37652. /**
  37653. * Amount of grain to be applied by the grain effect.
  37654. */
  37655. get: function () {
  37656. return this._grainIntensity;
  37657. },
  37658. set: function (value) {
  37659. if (this._grainIntensity === value) {
  37660. return;
  37661. }
  37662. this._grainIntensity = value;
  37663. },
  37664. enumerable: true,
  37665. configurable: true
  37666. });
  37667. Object.defineProperty(ImageProcessingConfiguration.prototype, "grainAnimated", {
  37668. /**
  37669. * If the grain effect should be animated.
  37670. */
  37671. get: function () {
  37672. return this._grainAnimated;
  37673. },
  37674. set: function (value) {
  37675. if (this._grainAnimated === value) {
  37676. return;
  37677. }
  37678. this._grainAnimated = value;
  37679. this._updateParameters();
  37680. },
  37681. enumerable: true,
  37682. configurable: true
  37683. });
  37684. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  37685. /**
  37686. * Gets the vignette blend mode allowing different kind of effect.
  37687. */
  37688. get: function () {
  37689. return this._vignetteBlendMode;
  37690. },
  37691. /**
  37692. * Sets the vignette blend mode allowing different kind of effect.
  37693. */
  37694. set: function (value) {
  37695. if (this._vignetteBlendMode === value) {
  37696. return;
  37697. }
  37698. this._vignetteBlendMode = value;
  37699. this._updateParameters();
  37700. },
  37701. enumerable: true,
  37702. configurable: true
  37703. });
  37704. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  37705. /**
  37706. * Gets wether the vignette effect is enabled.
  37707. */
  37708. get: function () {
  37709. return this._vignetteEnabled;
  37710. },
  37711. /**
  37712. * Sets wether the vignette effect is enabled.
  37713. */
  37714. set: function (value) {
  37715. if (this._vignetteEnabled === value) {
  37716. return;
  37717. }
  37718. this._vignetteEnabled = value;
  37719. this._updateParameters();
  37720. },
  37721. enumerable: true,
  37722. configurable: true
  37723. });
  37724. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  37725. /**
  37726. * Gets wether the image processing is applied through a post process or not.
  37727. */
  37728. get: function () {
  37729. return this._applyByPostProcess;
  37730. },
  37731. /**
  37732. * Sets wether the image processing is applied through a post process or not.
  37733. */
  37734. set: function (value) {
  37735. if (this._applyByPostProcess === value) {
  37736. return;
  37737. }
  37738. this._applyByPostProcess = value;
  37739. this._updateParameters();
  37740. },
  37741. enumerable: true,
  37742. configurable: true
  37743. });
  37744. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  37745. /**
  37746. * Gets wether the image processing is enabled or not.
  37747. */
  37748. get: function () {
  37749. return this._isEnabled;
  37750. },
  37751. /**
  37752. * Sets wether the image processing is enabled or not.
  37753. */
  37754. set: function (value) {
  37755. if (this._isEnabled === value) {
  37756. return;
  37757. }
  37758. this._isEnabled = value;
  37759. this._updateParameters();
  37760. },
  37761. enumerable: true,
  37762. configurable: true
  37763. });
  37764. /**
  37765. * Method called each time the image processing information changes requires to recompile the effect.
  37766. */
  37767. ImageProcessingConfiguration.prototype._updateParameters = function () {
  37768. this.onUpdateParameters.notifyObservers(this);
  37769. };
  37770. ImageProcessingConfiguration.prototype.getClassName = function () {
  37771. return "ImageProcessingConfiguration";
  37772. };
  37773. /**
  37774. * Prepare the list of uniforms associated with the Image Processing effects.
  37775. * @param uniformsList The list of uniforms used in the effect
  37776. * @param defines the list of defines currently in use
  37777. */
  37778. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  37779. if (defines.EXPOSURE) {
  37780. uniforms.push("exposureLinear");
  37781. }
  37782. if (defines.CONTRAST) {
  37783. uniforms.push("contrast");
  37784. }
  37785. if (defines.COLORGRADING) {
  37786. uniforms.push("colorTransformSettings");
  37787. }
  37788. if (defines.VIGNETTE) {
  37789. uniforms.push("vInverseScreenSize");
  37790. uniforms.push("vignetteSettings1");
  37791. uniforms.push("vignetteSettings2");
  37792. }
  37793. if (defines.COLORCURVES) {
  37794. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  37795. }
  37796. if (defines.GRAIN) {
  37797. uniforms.push("grainVarianceAmount");
  37798. uniforms.push("grainAnimatedSeed");
  37799. }
  37800. };
  37801. /**
  37802. * Prepare the list of samplers associated with the Image Processing effects.
  37803. * @param uniformsList The list of uniforms used in the effect
  37804. * @param defines the list of defines currently in use
  37805. */
  37806. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  37807. if (defines.COLORGRADING) {
  37808. samplersList.push("txColorTransform");
  37809. }
  37810. };
  37811. /**
  37812. * Prepare the list of defines associated to the shader.
  37813. * @param defines the list of defines to complete
  37814. */
  37815. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  37816. if (forPostProcess === void 0) { forPostProcess = false; }
  37817. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  37818. defines.VIGNETTE = false;
  37819. defines.TONEMAPPING = false;
  37820. defines.CONTRAST = false;
  37821. defines.EXPOSURE = false;
  37822. defines.COLORCURVES = false;
  37823. defines.COLORGRADING = false;
  37824. defines.COLORGRADING3D = false;
  37825. defines.IMAGEPROCESSING = false;
  37826. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  37827. return;
  37828. }
  37829. defines.VIGNETTE = this.vignetteEnabled;
  37830. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  37831. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  37832. defines.TONEMAPPING = this.toneMappingEnabled;
  37833. defines.CONTRAST = (this.contrast !== 1.0);
  37834. defines.EXPOSURE = (this.exposure !== 1.0);
  37835. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  37836. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  37837. if (defines.COLORGRADING) {
  37838. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  37839. }
  37840. else {
  37841. defines.COLORGRADING3D = false;
  37842. }
  37843. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  37844. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  37845. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  37846. defines.GRAIN = this.grainEnabled;
  37847. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING || defines.GRAIN;
  37848. };
  37849. /**
  37850. * Returns true if all the image processing information are ready.
  37851. */
  37852. ImageProcessingConfiguration.prototype.isReady = function () {
  37853. // Color Grading texure can not be none blocking.
  37854. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  37855. };
  37856. /**
  37857. * Binds the image processing to the shader.
  37858. * @param effect The effect to bind to
  37859. */
  37860. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  37861. if (aspectRatio === void 0) { aspectRatio = 1; }
  37862. // Color Curves
  37863. if (this._colorCurvesEnabled && this.colorCurves) {
  37864. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  37865. }
  37866. // Vignette
  37867. if (this._vignetteEnabled) {
  37868. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  37869. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  37870. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  37871. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  37872. var vignetteScaleX = vignetteScaleY * aspectRatio;
  37873. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  37874. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  37875. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  37876. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  37877. var vignettePower = -2.0 * this.vignetteWeight;
  37878. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  37879. }
  37880. // Exposure
  37881. effect.setFloat("exposureLinear", this.exposure);
  37882. // Contrast
  37883. effect.setFloat("contrast", this.contrast);
  37884. // Color transform settings
  37885. if (this.colorGradingTexture) {
  37886. effect.setTexture("txColorTransform", this.colorGradingTexture);
  37887. var textureSize = this.colorGradingTexture.getSize().height;
  37888. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  37889. 0.5 / textureSize, // textureOffset
  37890. textureSize, // textureSize
  37891. this.colorGradingTexture.level // weight
  37892. );
  37893. }
  37894. effect.setFloat("grainVarianceAmount", this.grainIntensity);
  37895. effect.setFloat("grainAnimatedSeed", this.grainAnimated ? Math.random() + 1 : 1);
  37896. };
  37897. /**
  37898. * Clones the current image processing instance.
  37899. * @return The cloned image processing
  37900. */
  37901. ImageProcessingConfiguration.prototype.clone = function () {
  37902. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  37903. };
  37904. /**
  37905. * Serializes the current image processing instance to a json representation.
  37906. * @return a JSON representation
  37907. */
  37908. ImageProcessingConfiguration.prototype.serialize = function () {
  37909. return BABYLON.SerializationHelper.Serialize(this);
  37910. };
  37911. /**
  37912. * Parses the image processing from a json representation.
  37913. * @param source the JSON source to parse
  37914. * @return The parsed image processing
  37915. */
  37916. ImageProcessingConfiguration.Parse = function (source) {
  37917. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  37918. };
  37919. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  37920. /**
  37921. * Used to apply the vignette as a mix with the pixel color.
  37922. */
  37923. get: function () {
  37924. return this._VIGNETTEMODE_MULTIPLY;
  37925. },
  37926. enumerable: true,
  37927. configurable: true
  37928. });
  37929. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  37930. /**
  37931. * Used to apply the vignette as a replacement of the pixel color.
  37932. */
  37933. get: function () {
  37934. return this._VIGNETTEMODE_OPAQUE;
  37935. },
  37936. enumerable: true,
  37937. configurable: true
  37938. });
  37939. // Static constants associated to the image processing.
  37940. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  37941. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  37942. __decorate([
  37943. BABYLON.serializeAsColorCurves()
  37944. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  37945. __decorate([
  37946. BABYLON.serialize()
  37947. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  37948. __decorate([
  37949. BABYLON.serializeAsTexture()
  37950. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  37951. __decorate([
  37952. BABYLON.serialize()
  37953. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  37954. __decorate([
  37955. BABYLON.serialize()
  37956. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  37957. __decorate([
  37958. BABYLON.serialize()
  37959. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  37960. __decorate([
  37961. BABYLON.serialize()
  37962. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  37963. __decorate([
  37964. BABYLON.serialize()
  37965. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  37966. __decorate([
  37967. BABYLON.serialize()
  37968. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  37969. __decorate([
  37970. BABYLON.serialize()
  37971. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  37972. __decorate([
  37973. BABYLON.serialize()
  37974. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  37975. __decorate([
  37976. BABYLON.serialize()
  37977. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  37978. __decorate([
  37979. BABYLON.serialize()
  37980. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  37981. __decorate([
  37982. BABYLON.serializeAsColor4()
  37983. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  37984. __decorate([
  37985. BABYLON.serialize()
  37986. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  37987. __decorate([
  37988. BABYLON.serialize()
  37989. ], ImageProcessingConfiguration.prototype, "_grainEnabled", void 0);
  37990. __decorate([
  37991. BABYLON.serialize()
  37992. ], ImageProcessingConfiguration.prototype, "_grainIntensity", void 0);
  37993. __decorate([
  37994. BABYLON.serialize()
  37995. ], ImageProcessingConfiguration.prototype, "_grainAnimated", void 0);
  37996. __decorate([
  37997. BABYLON.serialize()
  37998. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  37999. __decorate([
  38000. BABYLON.serialize()
  38001. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  38002. __decorate([
  38003. BABYLON.serialize()
  38004. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  38005. __decorate([
  38006. BABYLON.serialize()
  38007. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  38008. return ImageProcessingConfiguration;
  38009. }());
  38010. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  38011. })(BABYLON || (BABYLON = {}));
  38012. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  38013. "use strict";
  38014. var BABYLON;
  38015. (function (BABYLON) {
  38016. /**
  38017. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  38018. * It can help converting any input color in a desired output one. This can then be used to create effects
  38019. * from sepia, black and white to sixties or futuristic rendering...
  38020. *
  38021. * The only supported format is currently 3dl.
  38022. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  38023. */
  38024. var ColorGradingTexture = /** @class */ (function (_super) {
  38025. __extends(ColorGradingTexture, _super);
  38026. /**
  38027. * Instantiates a ColorGradingTexture from the following parameters.
  38028. *
  38029. * @param url The location of the color gradind data (currently only supporting 3dl)
  38030. * @param scene The scene the texture will be used in
  38031. */
  38032. function ColorGradingTexture(url, scene) {
  38033. var _this = _super.call(this, scene) || this;
  38034. if (!url) {
  38035. return _this;
  38036. }
  38037. _this._engine = scene.getEngine();
  38038. _this._textureMatrix = BABYLON.Matrix.Identity();
  38039. _this.name = url;
  38040. _this.url = url;
  38041. _this.hasAlpha = false;
  38042. _this.isCube = false;
  38043. _this.is3D = _this._engine.webGLVersion > 1;
  38044. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38045. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38046. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38047. _this.anisotropicFilteringLevel = 1;
  38048. _this._texture = _this._getFromCache(url, true);
  38049. if (!_this._texture) {
  38050. if (!scene.useDelayedTextureLoading) {
  38051. _this.loadTexture();
  38052. }
  38053. else {
  38054. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  38055. }
  38056. }
  38057. return _this;
  38058. }
  38059. /**
  38060. * Returns the texture matrix used in most of the material.
  38061. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  38062. */
  38063. ColorGradingTexture.prototype.getTextureMatrix = function () {
  38064. return this._textureMatrix;
  38065. };
  38066. /**
  38067. * Occurs when the file being loaded is a .3dl LUT file.
  38068. */
  38069. ColorGradingTexture.prototype.load3dlTexture = function () {
  38070. var engine = this._engine;
  38071. var texture;
  38072. if (engine.webGLVersion === 1) {
  38073. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  38074. }
  38075. else {
  38076. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  38077. }
  38078. this._texture = texture;
  38079. var callback = function (text) {
  38080. if (typeof text !== "string") {
  38081. return;
  38082. }
  38083. var data = null;
  38084. var tempData = null;
  38085. var line;
  38086. var lines = text.split('\n');
  38087. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  38088. var maxColor = 0;
  38089. for (var i = 0; i < lines.length; i++) {
  38090. line = lines[i];
  38091. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  38092. continue;
  38093. if (line.indexOf('#') === 0)
  38094. continue;
  38095. var words = line.split(" ");
  38096. if (size === 0) {
  38097. // Number of space + one
  38098. size = words.length;
  38099. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  38100. tempData = new Float32Array(size * size * size * 4);
  38101. continue;
  38102. }
  38103. if (size != 0) {
  38104. var r = Math.max(parseInt(words[0]), 0);
  38105. var g = Math.max(parseInt(words[1]), 0);
  38106. var b = Math.max(parseInt(words[2]), 0);
  38107. maxColor = Math.max(r, maxColor);
  38108. maxColor = Math.max(g, maxColor);
  38109. maxColor = Math.max(b, maxColor);
  38110. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  38111. if (tempData) {
  38112. tempData[pixelStorageIndex + 0] = r;
  38113. tempData[pixelStorageIndex + 1] = g;
  38114. tempData[pixelStorageIndex + 2] = b;
  38115. }
  38116. pixelIndexSlice++;
  38117. if (pixelIndexSlice % size == 0) {
  38118. pixelIndexH++;
  38119. pixelIndexSlice = 0;
  38120. if (pixelIndexH % size == 0) {
  38121. pixelIndexW++;
  38122. pixelIndexH = 0;
  38123. }
  38124. }
  38125. }
  38126. }
  38127. if (tempData && data) {
  38128. for (var i = 0; i < tempData.length; i++) {
  38129. if (i > 0 && (i + 1) % 4 === 0) {
  38130. data[i] = 255;
  38131. }
  38132. else {
  38133. var value = tempData[i];
  38134. data[i] = (value / maxColor * 255);
  38135. }
  38136. }
  38137. }
  38138. if (texture.is3D) {
  38139. texture.updateSize(size, size, size);
  38140. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  38141. }
  38142. else {
  38143. texture.updateSize(size * size, size);
  38144. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  38145. }
  38146. };
  38147. var scene = this.getScene();
  38148. if (scene) {
  38149. scene._loadFile(this.url, callback);
  38150. }
  38151. else {
  38152. this._engine._loadFile(this.url, callback);
  38153. }
  38154. return this._texture;
  38155. };
  38156. /**
  38157. * Starts the loading process of the texture.
  38158. */
  38159. ColorGradingTexture.prototype.loadTexture = function () {
  38160. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  38161. this.load3dlTexture();
  38162. }
  38163. };
  38164. /**
  38165. * Clones the color gradind texture.
  38166. */
  38167. ColorGradingTexture.prototype.clone = function () {
  38168. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  38169. // Base texture
  38170. newTexture.level = this.level;
  38171. return newTexture;
  38172. };
  38173. /**
  38174. * Called during delayed load for textures.
  38175. */
  38176. ColorGradingTexture.prototype.delayLoad = function () {
  38177. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  38178. return;
  38179. }
  38180. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  38181. this._texture = this._getFromCache(this.url, true);
  38182. if (!this._texture) {
  38183. this.loadTexture();
  38184. }
  38185. };
  38186. /**
  38187. * Parses a color grading texture serialized by Babylon.
  38188. * @param parsedTexture The texture information being parsedTexture
  38189. * @param scene The scene to load the texture in
  38190. * @param rootUrl The root url of the data assets to load
  38191. * @return A color gradind texture
  38192. */
  38193. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  38194. var texture = null;
  38195. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  38196. texture = new ColorGradingTexture(parsedTexture.name, scene);
  38197. texture.name = parsedTexture.name;
  38198. texture.level = parsedTexture.level;
  38199. }
  38200. return texture;
  38201. };
  38202. /**
  38203. * Serializes the LUT texture to json format.
  38204. */
  38205. ColorGradingTexture.prototype.serialize = function () {
  38206. if (!this.name) {
  38207. return null;
  38208. }
  38209. var serializationObject = {};
  38210. serializationObject.name = this.name;
  38211. serializationObject.level = this.level;
  38212. serializationObject.customType = "BABYLON.ColorGradingTexture";
  38213. return serializationObject;
  38214. };
  38215. /**
  38216. * Empty line regex stored for GC.
  38217. */
  38218. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  38219. return ColorGradingTexture;
  38220. }(BABYLON.BaseTexture));
  38221. BABYLON.ColorGradingTexture = ColorGradingTexture;
  38222. })(BABYLON || (BABYLON = {}));
  38223. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  38224. "use strict";
  38225. var BABYLON;
  38226. (function (BABYLON) {
  38227. /**
  38228. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  38229. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  38230. * 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;
  38231. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  38232. */
  38233. var ColorCurves = /** @class */ (function () {
  38234. function ColorCurves() {
  38235. this._dirty = true;
  38236. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  38237. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  38238. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  38239. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  38240. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  38241. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  38242. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  38243. this._globalHue = 30;
  38244. this._globalDensity = 0;
  38245. this._globalSaturation = 0;
  38246. this._globalExposure = 0;
  38247. this._highlightsHue = 30;
  38248. this._highlightsDensity = 0;
  38249. this._highlightsSaturation = 0;
  38250. this._highlightsExposure = 0;
  38251. this._midtonesHue = 30;
  38252. this._midtonesDensity = 0;
  38253. this._midtonesSaturation = 0;
  38254. this._midtonesExposure = 0;
  38255. this._shadowsHue = 30;
  38256. this._shadowsDensity = 0;
  38257. this._shadowsSaturation = 0;
  38258. this._shadowsExposure = 0;
  38259. }
  38260. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  38261. /**
  38262. * Gets the global Hue value.
  38263. * 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).
  38264. */
  38265. get: function () {
  38266. return this._globalHue;
  38267. },
  38268. /**
  38269. * Sets the global Hue value.
  38270. * 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).
  38271. */
  38272. set: function (value) {
  38273. this._globalHue = value;
  38274. this._dirty = true;
  38275. },
  38276. enumerable: true,
  38277. configurable: true
  38278. });
  38279. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  38280. /**
  38281. * Gets the global Density value.
  38282. * 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.
  38283. * Values less than zero provide a filter of opposite hue.
  38284. */
  38285. get: function () {
  38286. return this._globalDensity;
  38287. },
  38288. /**
  38289. * Sets the global Density value.
  38290. * 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.
  38291. * Values less than zero provide a filter of opposite hue.
  38292. */
  38293. set: function (value) {
  38294. this._globalDensity = value;
  38295. this._dirty = true;
  38296. },
  38297. enumerable: true,
  38298. configurable: true
  38299. });
  38300. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  38301. /**
  38302. * Gets the global Saturation value.
  38303. * 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.
  38304. */
  38305. get: function () {
  38306. return this._globalSaturation;
  38307. },
  38308. /**
  38309. * Sets the global Saturation value.
  38310. * 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.
  38311. */
  38312. set: function (value) {
  38313. this._globalSaturation = value;
  38314. this._dirty = true;
  38315. },
  38316. enumerable: true,
  38317. configurable: true
  38318. });
  38319. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  38320. /**
  38321. * Gets the highlights Hue value.
  38322. * 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).
  38323. */
  38324. get: function () {
  38325. return this._highlightsHue;
  38326. },
  38327. /**
  38328. * Sets the highlights Hue value.
  38329. * 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).
  38330. */
  38331. set: function (value) {
  38332. this._highlightsHue = value;
  38333. this._dirty = true;
  38334. },
  38335. enumerable: true,
  38336. configurable: true
  38337. });
  38338. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  38339. /**
  38340. * Gets the highlights Density value.
  38341. * 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.
  38342. * Values less than zero provide a filter of opposite hue.
  38343. */
  38344. get: function () {
  38345. return this._highlightsDensity;
  38346. },
  38347. /**
  38348. * Sets the highlights Density value.
  38349. * 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.
  38350. * Values less than zero provide a filter of opposite hue.
  38351. */
  38352. set: function (value) {
  38353. this._highlightsDensity = value;
  38354. this._dirty = true;
  38355. },
  38356. enumerable: true,
  38357. configurable: true
  38358. });
  38359. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  38360. /**
  38361. * Gets the highlights Saturation value.
  38362. * 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.
  38363. */
  38364. get: function () {
  38365. return this._highlightsSaturation;
  38366. },
  38367. /**
  38368. * Sets the highlights Saturation value.
  38369. * 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.
  38370. */
  38371. set: function (value) {
  38372. this._highlightsSaturation = value;
  38373. this._dirty = true;
  38374. },
  38375. enumerable: true,
  38376. configurable: true
  38377. });
  38378. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  38379. /**
  38380. * Gets the highlights Exposure value.
  38381. * 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.
  38382. */
  38383. get: function () {
  38384. return this._highlightsExposure;
  38385. },
  38386. /**
  38387. * Sets the highlights Exposure value.
  38388. * 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.
  38389. */
  38390. set: function (value) {
  38391. this._highlightsExposure = value;
  38392. this._dirty = true;
  38393. },
  38394. enumerable: true,
  38395. configurable: true
  38396. });
  38397. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  38398. /**
  38399. * Gets the midtones Hue value.
  38400. * 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).
  38401. */
  38402. get: function () {
  38403. return this._midtonesHue;
  38404. },
  38405. /**
  38406. * Sets the midtones Hue value.
  38407. * 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).
  38408. */
  38409. set: function (value) {
  38410. this._midtonesHue = value;
  38411. this._dirty = true;
  38412. },
  38413. enumerable: true,
  38414. configurable: true
  38415. });
  38416. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  38417. /**
  38418. * Gets the midtones Density value.
  38419. * 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.
  38420. * Values less than zero provide a filter of opposite hue.
  38421. */
  38422. get: function () {
  38423. return this._midtonesDensity;
  38424. },
  38425. /**
  38426. * Sets the midtones Density value.
  38427. * 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.
  38428. * Values less than zero provide a filter of opposite hue.
  38429. */
  38430. set: function (value) {
  38431. this._midtonesDensity = value;
  38432. this._dirty = true;
  38433. },
  38434. enumerable: true,
  38435. configurable: true
  38436. });
  38437. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  38438. /**
  38439. * Gets the midtones Saturation value.
  38440. * 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.
  38441. */
  38442. get: function () {
  38443. return this._midtonesSaturation;
  38444. },
  38445. /**
  38446. * Sets the midtones Saturation value.
  38447. * 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.
  38448. */
  38449. set: function (value) {
  38450. this._midtonesSaturation = value;
  38451. this._dirty = true;
  38452. },
  38453. enumerable: true,
  38454. configurable: true
  38455. });
  38456. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  38457. /**
  38458. * Gets the midtones Exposure value.
  38459. * 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.
  38460. */
  38461. get: function () {
  38462. return this._midtonesExposure;
  38463. },
  38464. /**
  38465. * Sets the midtones Exposure value.
  38466. * 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.
  38467. */
  38468. set: function (value) {
  38469. this._midtonesExposure = value;
  38470. this._dirty = true;
  38471. },
  38472. enumerable: true,
  38473. configurable: true
  38474. });
  38475. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  38476. /**
  38477. * Gets the shadows Hue value.
  38478. * 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).
  38479. */
  38480. get: function () {
  38481. return this._shadowsHue;
  38482. },
  38483. /**
  38484. * Sets the shadows Hue value.
  38485. * 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).
  38486. */
  38487. set: function (value) {
  38488. this._shadowsHue = value;
  38489. this._dirty = true;
  38490. },
  38491. enumerable: true,
  38492. configurable: true
  38493. });
  38494. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  38495. /**
  38496. * Gets the shadows Density value.
  38497. * 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.
  38498. * Values less than zero provide a filter of opposite hue.
  38499. */
  38500. get: function () {
  38501. return this._shadowsDensity;
  38502. },
  38503. /**
  38504. * Sets the shadows Density value.
  38505. * 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.
  38506. * Values less than zero provide a filter of opposite hue.
  38507. */
  38508. set: function (value) {
  38509. this._shadowsDensity = value;
  38510. this._dirty = true;
  38511. },
  38512. enumerable: true,
  38513. configurable: true
  38514. });
  38515. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  38516. /**
  38517. * Gets the shadows Saturation value.
  38518. * 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.
  38519. */
  38520. get: function () {
  38521. return this._shadowsSaturation;
  38522. },
  38523. /**
  38524. * Sets the shadows Saturation value.
  38525. * 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.
  38526. */
  38527. set: function (value) {
  38528. this._shadowsSaturation = value;
  38529. this._dirty = true;
  38530. },
  38531. enumerable: true,
  38532. configurable: true
  38533. });
  38534. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  38535. /**
  38536. * Gets the shadows Exposure value.
  38537. * 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.
  38538. */
  38539. get: function () {
  38540. return this._shadowsExposure;
  38541. },
  38542. /**
  38543. * Sets the shadows Exposure value.
  38544. * 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.
  38545. */
  38546. set: function (value) {
  38547. this._shadowsExposure = value;
  38548. this._dirty = true;
  38549. },
  38550. enumerable: true,
  38551. configurable: true
  38552. });
  38553. ColorCurves.prototype.getClassName = function () {
  38554. return "ColorCurves";
  38555. };
  38556. /**
  38557. * Binds the color curves to the shader.
  38558. * @param colorCurves The color curve to bind
  38559. * @param effect The effect to bind to
  38560. */
  38561. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  38562. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  38563. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  38564. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  38565. if (colorCurves._dirty) {
  38566. colorCurves._dirty = false;
  38567. // Fill in global info.
  38568. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  38569. // Compute highlights info.
  38570. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  38571. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  38572. // Compute midtones info.
  38573. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  38574. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  38575. // Compute shadows info.
  38576. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  38577. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  38578. // Compute deltas (neutral is midtones).
  38579. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  38580. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  38581. }
  38582. if (effect) {
  38583. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  38584. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  38585. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  38586. }
  38587. };
  38588. /**
  38589. * Prepare the list of uniforms associated with the ColorCurves effects.
  38590. * @param uniformsList The list of uniforms used in the effect
  38591. */
  38592. ColorCurves.PrepareUniforms = function (uniformsList) {
  38593. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  38594. };
  38595. /**
  38596. * Returns color grading data based on a hue, density, saturation and exposure value.
  38597. * @param filterHue The hue of the color filter.
  38598. * @param filterDensity The density of the color filter.
  38599. * @param saturation The saturation.
  38600. * @param exposure The exposure.
  38601. * @param result The result data container.
  38602. */
  38603. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  38604. if (hue == null) {
  38605. return;
  38606. }
  38607. hue = ColorCurves.clamp(hue, 0, 360);
  38608. density = ColorCurves.clamp(density, -100, 100);
  38609. saturation = ColorCurves.clamp(saturation, -100, 100);
  38610. exposure = ColorCurves.clamp(exposure, -100, 100);
  38611. // Remap the slider/config filter density with non-linear mapping and also scale by half
  38612. // so that the maximum filter density is only 50% control. This provides fine control
  38613. // for small values and reasonable range.
  38614. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  38615. density *= 0.5;
  38616. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  38617. if (density < 0) {
  38618. density *= -1;
  38619. hue = (hue + 180) % 360;
  38620. }
  38621. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  38622. result.scaleToRef(2, result);
  38623. result.a = 1 + 0.01 * saturation;
  38624. };
  38625. /**
  38626. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  38627. * @param value The input slider value in range [-100,100].
  38628. * @returns Adjusted value.
  38629. */
  38630. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  38631. value /= 100;
  38632. var x = Math.abs(value);
  38633. x = Math.pow(x, 2);
  38634. if (value < 0) {
  38635. x *= -1;
  38636. }
  38637. x *= 100;
  38638. return x;
  38639. };
  38640. /**
  38641. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  38642. * @param hue The hue (H) input.
  38643. * @param saturation The saturation (S) input.
  38644. * @param brightness The brightness (B) input.
  38645. * @result An RGBA color represented as Vector4.
  38646. */
  38647. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  38648. var h = ColorCurves.clamp(hue, 0, 360);
  38649. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  38650. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  38651. if (s === 0) {
  38652. result.r = v;
  38653. result.g = v;
  38654. result.b = v;
  38655. }
  38656. else {
  38657. // sector 0 to 5
  38658. h /= 60;
  38659. var i = Math.floor(h);
  38660. // fractional part of h
  38661. var f = h - i;
  38662. var p = v * (1 - s);
  38663. var q = v * (1 - s * f);
  38664. var t = v * (1 - s * (1 - f));
  38665. switch (i) {
  38666. case 0:
  38667. result.r = v;
  38668. result.g = t;
  38669. result.b = p;
  38670. break;
  38671. case 1:
  38672. result.r = q;
  38673. result.g = v;
  38674. result.b = p;
  38675. break;
  38676. case 2:
  38677. result.r = p;
  38678. result.g = v;
  38679. result.b = t;
  38680. break;
  38681. case 3:
  38682. result.r = p;
  38683. result.g = q;
  38684. result.b = v;
  38685. break;
  38686. case 4:
  38687. result.r = t;
  38688. result.g = p;
  38689. result.b = v;
  38690. break;
  38691. default:// case 5:
  38692. result.r = v;
  38693. result.g = p;
  38694. result.b = q;
  38695. break;
  38696. }
  38697. }
  38698. result.a = 1;
  38699. };
  38700. /**
  38701. * Returns a value clamped between min and max
  38702. * @param value The value to clamp
  38703. * @param min The minimum of value
  38704. * @param max The maximum of value
  38705. * @returns The clamped value.
  38706. */
  38707. ColorCurves.clamp = function (value, min, max) {
  38708. return Math.min(Math.max(value, min), max);
  38709. };
  38710. /**
  38711. * Clones the current color curve instance.
  38712. * @return The cloned curves
  38713. */
  38714. ColorCurves.prototype.clone = function () {
  38715. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  38716. };
  38717. /**
  38718. * Serializes the current color curve instance to a json representation.
  38719. * @return a JSON representation
  38720. */
  38721. ColorCurves.prototype.serialize = function () {
  38722. return BABYLON.SerializationHelper.Serialize(this);
  38723. };
  38724. /**
  38725. * Parses the color curve from a json representation.
  38726. * @param source the JSON source to parse
  38727. * @return The parsed curves
  38728. */
  38729. ColorCurves.Parse = function (source) {
  38730. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  38731. };
  38732. __decorate([
  38733. BABYLON.serialize()
  38734. ], ColorCurves.prototype, "_globalHue", void 0);
  38735. __decorate([
  38736. BABYLON.serialize()
  38737. ], ColorCurves.prototype, "_globalDensity", void 0);
  38738. __decorate([
  38739. BABYLON.serialize()
  38740. ], ColorCurves.prototype, "_globalSaturation", void 0);
  38741. __decorate([
  38742. BABYLON.serialize()
  38743. ], ColorCurves.prototype, "_globalExposure", void 0);
  38744. __decorate([
  38745. BABYLON.serialize()
  38746. ], ColorCurves.prototype, "_highlightsHue", void 0);
  38747. __decorate([
  38748. BABYLON.serialize()
  38749. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  38750. __decorate([
  38751. BABYLON.serialize()
  38752. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  38753. __decorate([
  38754. BABYLON.serialize()
  38755. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  38756. __decorate([
  38757. BABYLON.serialize()
  38758. ], ColorCurves.prototype, "_midtonesHue", void 0);
  38759. __decorate([
  38760. BABYLON.serialize()
  38761. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  38762. __decorate([
  38763. BABYLON.serialize()
  38764. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  38765. __decorate([
  38766. BABYLON.serialize()
  38767. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  38768. return ColorCurves;
  38769. }());
  38770. BABYLON.ColorCurves = ColorCurves;
  38771. })(BABYLON || (BABYLON = {}));
  38772. //# sourceMappingURL=babylon.colorCurves.js.map
  38773. "use strict";
  38774. //# sourceMappingURL=babylon.behavior.js.map
  38775. "use strict";
  38776. var BABYLON;
  38777. (function (BABYLON) {
  38778. /**
  38779. * "Static Class" containing the most commonly used helper while dealing with material for
  38780. * rendering purpose.
  38781. *
  38782. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  38783. *
  38784. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  38785. */
  38786. var MaterialHelper = /** @class */ (function () {
  38787. function MaterialHelper() {
  38788. }
  38789. /**
  38790. * Bind the current view position to an effect.
  38791. * @param effect The effect to be bound
  38792. * @param scene The scene the eyes position is used from
  38793. */
  38794. MaterialHelper.BindEyePosition = function (effect, scene) {
  38795. if (scene._forcedViewPosition) {
  38796. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  38797. return;
  38798. }
  38799. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  38800. };
  38801. /**
  38802. * Helps preparing the defines values about the UVs in used in the effect.
  38803. * UVs are shared as much as we can accross chanels in the shaders.
  38804. * @param texture The texture we are preparing the UVs for
  38805. * @param defines The defines to update
  38806. * @param key The chanel key "diffuse", "specular"... used in the shader
  38807. */
  38808. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  38809. defines._needUVs = true;
  38810. defines[key] = true;
  38811. if (texture.getTextureMatrix().isIdentity(true)) {
  38812. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  38813. if (texture.coordinatesIndex === 0) {
  38814. defines["MAINUV1"] = true;
  38815. }
  38816. else {
  38817. defines["MAINUV2"] = true;
  38818. }
  38819. }
  38820. else {
  38821. defines[key + "DIRECTUV"] = 0;
  38822. }
  38823. };
  38824. /**
  38825. * Binds a texture matrix value to its corrsponding uniform
  38826. * @param texture The texture to bind the matrix for
  38827. * @param uniformBuffer The uniform buffer receivin the data
  38828. * @param key The chanel key "diffuse", "specular"... used in the shader
  38829. */
  38830. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  38831. var matrix = texture.getTextureMatrix();
  38832. if (!matrix.isIdentity(true)) {
  38833. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  38834. }
  38835. };
  38836. /**
  38837. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  38838. * @param mesh defines the current mesh
  38839. * @param scene defines the current scene
  38840. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  38841. * @param pointsCloud defines if point cloud rendering has to be turned on
  38842. * @param fogEnabled defines if fog has to be turned on
  38843. * @param alphaTest defines if alpha testing has to be turned on
  38844. * @param defines defines the current list of defines
  38845. */
  38846. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  38847. if (defines._areMiscDirty) {
  38848. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  38849. defines["POINTSIZE"] = pointsCloud;
  38850. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  38851. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  38852. defines["ALPHATEST"] = alphaTest;
  38853. }
  38854. };
  38855. /**
  38856. * Helper used to prepare the list of defines associated with frame values for shader compilation
  38857. * @param scene defines the current scene
  38858. * @param engine defines the current engine
  38859. * @param defines specifies the list of active defines
  38860. * @param useInstances defines if instances have to be turned on
  38861. * @param useClipPlane defines if clip plane have to be turned on
  38862. */
  38863. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  38864. if (useClipPlane === void 0) { useClipPlane = null; }
  38865. var changed = false;
  38866. if (useClipPlane == null) {
  38867. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  38868. }
  38869. if (defines["CLIPPLANE"] !== useClipPlane) {
  38870. defines["CLIPPLANE"] = useClipPlane;
  38871. changed = true;
  38872. }
  38873. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  38874. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  38875. changed = true;
  38876. }
  38877. if (defines["INSTANCES"] !== useInstances) {
  38878. defines["INSTANCES"] = useInstances;
  38879. changed = true;
  38880. }
  38881. if (changed) {
  38882. defines.markAsUnprocessed();
  38883. }
  38884. };
  38885. /**
  38886. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  38887. * @param mesh The mesh containing the geometry data we will draw
  38888. * @param defines The defines to update
  38889. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  38890. * @param useBones Precise whether bones should be used or not (override mesh info)
  38891. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  38892. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  38893. * @returns false if defines are considered not dirty and have not been checked
  38894. */
  38895. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  38896. if (useMorphTargets === void 0) { useMorphTargets = false; }
  38897. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  38898. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  38899. return false;
  38900. }
  38901. defines._normals = defines._needNormals;
  38902. defines._uvs = defines._needUVs;
  38903. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  38904. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38905. defines["TANGENT"] = true;
  38906. }
  38907. if (defines._needUVs) {
  38908. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  38909. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  38910. }
  38911. else {
  38912. defines["UV1"] = false;
  38913. defines["UV2"] = false;
  38914. }
  38915. if (useVertexColor) {
  38916. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  38917. defines["VERTEXCOLOR"] = hasVertexColors;
  38918. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  38919. }
  38920. if (useBones) {
  38921. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  38922. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  38923. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  38924. }
  38925. else {
  38926. defines["NUM_BONE_INFLUENCERS"] = 0;
  38927. defines["BonesPerMesh"] = 0;
  38928. }
  38929. }
  38930. if (useMorphTargets) {
  38931. var manager = mesh.morphTargetManager;
  38932. if (manager) {
  38933. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  38934. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  38935. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  38936. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  38937. }
  38938. else {
  38939. defines["MORPHTARGETS_TANGENT"] = false;
  38940. defines["MORPHTARGETS_NORMAL"] = false;
  38941. defines["MORPHTARGETS"] = false;
  38942. defines["NUM_MORPH_INFLUENCERS"] = 0;
  38943. }
  38944. }
  38945. return true;
  38946. };
  38947. /**
  38948. * Prepares the defines related to the light information passed in parameter
  38949. * @param scene The scene we are intending to draw
  38950. * @param mesh The mesh the effect is compiling for
  38951. * @param defines The defines to update
  38952. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  38953. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  38954. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  38955. * @returns true if normals will be required for the rest of the effect
  38956. */
  38957. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  38958. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  38959. if (disableLighting === void 0) { disableLighting = false; }
  38960. if (!defines._areLightsDirty) {
  38961. return defines._needNormals;
  38962. }
  38963. var lightIndex = 0;
  38964. var needNormals = false;
  38965. var needRebuild = false;
  38966. var lightmapMode = false;
  38967. var shadowEnabled = false;
  38968. var specularEnabled = false;
  38969. if (scene.lightsEnabled && !disableLighting) {
  38970. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  38971. var light = _a[_i];
  38972. needNormals = true;
  38973. if (defines["LIGHT" + lightIndex] === undefined) {
  38974. needRebuild = true;
  38975. }
  38976. defines["LIGHT" + lightIndex] = true;
  38977. defines["SPOTLIGHT" + lightIndex] = false;
  38978. defines["HEMILIGHT" + lightIndex] = false;
  38979. defines["POINTLIGHT" + lightIndex] = false;
  38980. defines["DIRLIGHT" + lightIndex] = false;
  38981. var type;
  38982. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  38983. type = "SPOTLIGHT" + lightIndex;
  38984. var spotLight = light;
  38985. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? spotLight.projectionTexture.isReady() : false;
  38986. }
  38987. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  38988. type = "HEMILIGHT" + lightIndex;
  38989. }
  38990. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  38991. type = "POINTLIGHT" + lightIndex;
  38992. }
  38993. else {
  38994. type = "DIRLIGHT" + lightIndex;
  38995. }
  38996. defines[type] = true;
  38997. // Specular
  38998. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  38999. specularEnabled = true;
  39000. }
  39001. // Shadows
  39002. defines["SHADOW" + lightIndex] = false;
  39003. defines["SHADOWPCF" + lightIndex] = false;
  39004. defines["SHADOWPCSS" + lightIndex] = false;
  39005. defines["SHADOWPOISSON" + lightIndex] = false;
  39006. defines["SHADOWESM" + lightIndex] = false;
  39007. defines["SHADOWCUBE" + lightIndex] = false;
  39008. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  39009. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  39010. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  39011. var shadowGenerator = light.getShadowGenerator();
  39012. if (shadowGenerator) {
  39013. shadowEnabled = true;
  39014. shadowGenerator.prepareDefines(defines, lightIndex);
  39015. }
  39016. }
  39017. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  39018. lightmapMode = true;
  39019. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  39020. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  39021. }
  39022. else {
  39023. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  39024. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  39025. }
  39026. lightIndex++;
  39027. if (lightIndex === maxSimultaneousLights)
  39028. break;
  39029. }
  39030. }
  39031. defines["SPECULARTERM"] = specularEnabled;
  39032. defines["SHADOWS"] = shadowEnabled;
  39033. // Resetting all other lights if any
  39034. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  39035. if (defines["LIGHT" + index] !== undefined) {
  39036. defines["LIGHT" + index] = false;
  39037. defines["HEMILIGHT" + lightIndex] = false;
  39038. defines["POINTLIGHT" + lightIndex] = false;
  39039. defines["DIRLIGHT" + lightIndex] = false;
  39040. defines["SPOTLIGHT" + lightIndex] = false;
  39041. defines["SHADOW" + lightIndex] = false;
  39042. }
  39043. }
  39044. var caps = scene.getEngine().getCaps();
  39045. if (defines["SHADOWFLOAT"] === undefined) {
  39046. needRebuild = true;
  39047. }
  39048. defines["SHADOWFLOAT"] = shadowEnabled &&
  39049. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  39050. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  39051. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  39052. if (needRebuild) {
  39053. defines.rebuild();
  39054. }
  39055. return needNormals;
  39056. };
  39057. /**
  39058. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  39059. * that won t be acctive due to defines being turned off.
  39060. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  39061. * @param samplersList The samplers list
  39062. * @param defines The defines helping in the list generation
  39063. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  39064. */
  39065. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  39066. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39067. var uniformsList;
  39068. var uniformBuffersList = null;
  39069. if (uniformsListOrOptions.uniformsNames) {
  39070. var options = uniformsListOrOptions;
  39071. uniformsList = options.uniformsNames;
  39072. uniformBuffersList = options.uniformBuffersNames;
  39073. samplersList = options.samplers;
  39074. defines = options.defines;
  39075. maxSimultaneousLights = options.maxSimultaneousLights;
  39076. }
  39077. else {
  39078. uniformsList = uniformsListOrOptions;
  39079. if (!samplersList) {
  39080. samplersList = [];
  39081. }
  39082. }
  39083. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  39084. if (!defines["LIGHT" + lightIndex]) {
  39085. break;
  39086. }
  39087. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  39088. if (uniformBuffersList) {
  39089. uniformBuffersList.push("Light" + lightIndex);
  39090. }
  39091. samplersList.push("shadowSampler" + lightIndex);
  39092. samplersList.push("depthSampler" + lightIndex);
  39093. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  39094. samplersList.push("projectionLightSampler" + lightIndex);
  39095. uniformsList.push("textureProjectionMatrix" + lightIndex);
  39096. }
  39097. }
  39098. if (defines["NUM_MORPH_INFLUENCERS"]) {
  39099. uniformsList.push("morphTargetInfluences");
  39100. }
  39101. };
  39102. /**
  39103. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  39104. * @param defines The defines to update while falling back
  39105. * @param fallbacks The authorized effect fallbacks
  39106. * @param maxSimultaneousLights The maximum number of lights allowed
  39107. * @param rank the current rank of the Effect
  39108. * @returns The newly affected rank
  39109. */
  39110. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  39111. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39112. if (rank === void 0) { rank = 0; }
  39113. var lightFallbackRank = 0;
  39114. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  39115. if (!defines["LIGHT" + lightIndex]) {
  39116. break;
  39117. }
  39118. if (lightIndex > 0) {
  39119. lightFallbackRank = rank + lightIndex;
  39120. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  39121. }
  39122. if (!defines["SHADOWS"]) {
  39123. if (defines["SHADOW" + lightIndex]) {
  39124. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  39125. }
  39126. if (defines["SHADOWPCF" + lightIndex]) {
  39127. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  39128. }
  39129. if (defines["SHADOWPCSS" + lightIndex]) {
  39130. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  39131. }
  39132. if (defines["SHADOWPOISSON" + lightIndex]) {
  39133. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  39134. }
  39135. if (defines["SHADOWESM" + lightIndex]) {
  39136. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  39137. }
  39138. }
  39139. }
  39140. return lightFallbackRank++;
  39141. };
  39142. /**
  39143. * Prepares the list of attributes required for morph targets according to the effect defines.
  39144. * @param attribs The current list of supported attribs
  39145. * @param mesh The mesh to prepare the morph targets attributes for
  39146. * @param defines The current Defines of the effect
  39147. */
  39148. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  39149. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  39150. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  39151. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  39152. var manager = mesh.morphTargetManager;
  39153. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  39154. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  39155. for (var index = 0; index < influencers; index++) {
  39156. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  39157. if (normal) {
  39158. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  39159. }
  39160. if (tangent) {
  39161. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  39162. }
  39163. if (attribs.length > maxAttributesCount) {
  39164. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  39165. }
  39166. }
  39167. }
  39168. };
  39169. /**
  39170. * Prepares the list of attributes required for bones according to the effect defines.
  39171. * @param attribs The current list of supported attribs
  39172. * @param mesh The mesh to prepare the bones attributes for
  39173. * @param defines The current Defines of the effect
  39174. * @param fallbacks The current efffect fallback strategy
  39175. */
  39176. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  39177. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  39178. fallbacks.addCPUSkinningFallback(0, mesh);
  39179. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39180. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39181. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  39182. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39183. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  39184. }
  39185. }
  39186. };
  39187. /**
  39188. * Prepares the list of attributes required for instances according to the effect defines.
  39189. * @param attribs The current list of supported attribs
  39190. * @param defines The current Defines of the effect
  39191. */
  39192. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  39193. if (defines["INSTANCES"]) {
  39194. attribs.push("world0");
  39195. attribs.push("world1");
  39196. attribs.push("world2");
  39197. attribs.push("world3");
  39198. }
  39199. };
  39200. /**
  39201. * Binds the light shadow information to the effect for the given mesh.
  39202. * @param light The light containing the generator
  39203. * @param scene The scene the lights belongs to
  39204. * @param mesh The mesh we are binding the information to render
  39205. * @param lightIndex The light index in the effect used to render the mesh
  39206. * @param effect The effect we are binding the data to
  39207. */
  39208. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  39209. if (light.shadowEnabled && mesh.receiveShadows) {
  39210. var shadowGenerator = light.getShadowGenerator();
  39211. if (shadowGenerator) {
  39212. shadowGenerator.bindShadowLight(lightIndex, effect);
  39213. }
  39214. }
  39215. };
  39216. /**
  39217. * Binds the light information to the effect.
  39218. * @param light The light containing the generator
  39219. * @param effect The effect we are binding the data to
  39220. * @param lightIndex The light index in the effect used to render
  39221. */
  39222. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  39223. light.transferToEffect(effect, lightIndex + "");
  39224. };
  39225. /**
  39226. * Binds the lights information from the scene to the effect for the given mesh.
  39227. * @param scene The scene the lights belongs to
  39228. * @param mesh The mesh we are binding the information to render
  39229. * @param effect The effect we are binding the data to
  39230. * @param defines The generated defines for the effect
  39231. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  39232. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  39233. */
  39234. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  39235. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  39236. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  39237. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  39238. for (var i = 0; i < len; i++) {
  39239. var light = mesh._lightSources[i];
  39240. var iAsString = i.toString();
  39241. var scaledIntensity = light.getScaledIntensity();
  39242. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  39243. MaterialHelper.BindLightProperties(light, effect, i);
  39244. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  39245. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  39246. if (defines["SPECULARTERM"]) {
  39247. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  39248. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  39249. }
  39250. // Shadows
  39251. if (scene.shadowsEnabled) {
  39252. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  39253. }
  39254. light._uniformBuffer.update();
  39255. }
  39256. };
  39257. /**
  39258. * Binds the fog information from the scene to the effect for the given mesh.
  39259. * @param scene The scene the lights belongs to
  39260. * @param mesh The mesh we are binding the information to render
  39261. * @param effect The effect we are binding the data to
  39262. */
  39263. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  39264. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  39265. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  39266. effect.setColor3("vFogColor", scene.fogColor);
  39267. }
  39268. };
  39269. /**
  39270. * Binds the bones information from the mesh to the effect.
  39271. * @param mesh The mesh we are binding the information to render
  39272. * @param effect The effect we are binding the data to
  39273. */
  39274. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  39275. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  39276. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  39277. if (matrices && effect) {
  39278. effect.setMatrices("mBones", matrices);
  39279. }
  39280. }
  39281. };
  39282. /**
  39283. * Binds the morph targets information from the mesh to the effect.
  39284. * @param abstractMesh The mesh we are binding the information to render
  39285. * @param effect The effect we are binding the data to
  39286. */
  39287. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  39288. var manager = abstractMesh.morphTargetManager;
  39289. if (!abstractMesh || !manager) {
  39290. return;
  39291. }
  39292. effect.setFloatArray("morphTargetInfluences", manager.influences);
  39293. };
  39294. /**
  39295. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  39296. * @param defines The generated defines used in the effect
  39297. * @param effect The effect we are binding the data to
  39298. * @param scene The scene we are willing to render with logarithmic scale for
  39299. */
  39300. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  39301. if (defines["LOGARITHMICDEPTH"]) {
  39302. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  39303. }
  39304. };
  39305. /**
  39306. * Binds the clip plane information from the scene to the effect.
  39307. * @param scene The scene the clip plane information are extracted from
  39308. * @param effect The effect we are binding the data to
  39309. */
  39310. MaterialHelper.BindClipPlane = function (effect, scene) {
  39311. if (scene.clipPlane) {
  39312. var clipPlane = scene.clipPlane;
  39313. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  39314. }
  39315. };
  39316. return MaterialHelper;
  39317. }());
  39318. BABYLON.MaterialHelper = MaterialHelper;
  39319. })(BABYLON || (BABYLON = {}));
  39320. //# sourceMappingURL=babylon.materialHelper.js.map
  39321. "use strict";
  39322. var BABYLON;
  39323. (function (BABYLON) {
  39324. var PushMaterial = /** @class */ (function (_super) {
  39325. __extends(PushMaterial, _super);
  39326. function PushMaterial(name, scene) {
  39327. var _this = _super.call(this, name, scene) || this;
  39328. _this._normalMatrix = new BABYLON.Matrix();
  39329. _this.storeEffectOnSubMeshes = true;
  39330. return _this;
  39331. }
  39332. PushMaterial.prototype.getEffect = function () {
  39333. return this._activeEffect;
  39334. };
  39335. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  39336. if (!mesh) {
  39337. return false;
  39338. }
  39339. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  39340. return true;
  39341. }
  39342. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  39343. };
  39344. /**
  39345. * Binds the given world matrix to the active effect
  39346. *
  39347. * @param world the matrix to bind
  39348. */
  39349. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  39350. this._activeEffect.setMatrix("world", world);
  39351. };
  39352. /**
  39353. * Binds the given normal matrix to the active effect
  39354. *
  39355. * @param normalMatrix the matrix to bind
  39356. */
  39357. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  39358. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  39359. };
  39360. PushMaterial.prototype.bind = function (world, mesh) {
  39361. if (!mesh) {
  39362. return;
  39363. }
  39364. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  39365. };
  39366. PushMaterial.prototype._afterBind = function (mesh, effect) {
  39367. if (effect === void 0) { effect = null; }
  39368. _super.prototype._afterBind.call(this, mesh);
  39369. this.getScene()._cachedEffect = effect;
  39370. };
  39371. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  39372. if (visibility === void 0) { visibility = 1; }
  39373. return scene.isCachedMaterialInvalid(this, effect, visibility);
  39374. };
  39375. return PushMaterial;
  39376. }(BABYLON.Material));
  39377. BABYLON.PushMaterial = PushMaterial;
  39378. })(BABYLON || (BABYLON = {}));
  39379. //# sourceMappingURL=babylon.pushMaterial.js.map
  39380. "use strict";
  39381. var BABYLON;
  39382. (function (BABYLON) {
  39383. /** @ignore */
  39384. var StandardMaterialDefines = /** @class */ (function (_super) {
  39385. __extends(StandardMaterialDefines, _super);
  39386. function StandardMaterialDefines() {
  39387. var _this = _super.call(this) || this;
  39388. _this.MAINUV1 = false;
  39389. _this.MAINUV2 = false;
  39390. _this.DIFFUSE = false;
  39391. _this.DIFFUSEDIRECTUV = 0;
  39392. _this.AMBIENT = false;
  39393. _this.AMBIENTDIRECTUV = 0;
  39394. _this.OPACITY = false;
  39395. _this.OPACITYDIRECTUV = 0;
  39396. _this.OPACITYRGB = false;
  39397. _this.REFLECTION = false;
  39398. _this.EMISSIVE = false;
  39399. _this.EMISSIVEDIRECTUV = 0;
  39400. _this.SPECULAR = false;
  39401. _this.SPECULARDIRECTUV = 0;
  39402. _this.BUMP = false;
  39403. _this.BUMPDIRECTUV = 0;
  39404. _this.PARALLAX = false;
  39405. _this.PARALLAXOCCLUSION = false;
  39406. _this.SPECULAROVERALPHA = false;
  39407. _this.CLIPPLANE = false;
  39408. _this.ALPHATEST = false;
  39409. _this.DEPTHPREPASS = false;
  39410. _this.ALPHAFROMDIFFUSE = false;
  39411. _this.POINTSIZE = false;
  39412. _this.FOG = false;
  39413. _this.SPECULARTERM = false;
  39414. _this.DIFFUSEFRESNEL = false;
  39415. _this.OPACITYFRESNEL = false;
  39416. _this.REFLECTIONFRESNEL = false;
  39417. _this.REFRACTIONFRESNEL = false;
  39418. _this.EMISSIVEFRESNEL = false;
  39419. _this.FRESNEL = false;
  39420. _this.NORMAL = false;
  39421. _this.UV1 = false;
  39422. _this.UV2 = false;
  39423. _this.VERTEXCOLOR = false;
  39424. _this.VERTEXALPHA = false;
  39425. _this.NUM_BONE_INFLUENCERS = 0;
  39426. _this.BonesPerMesh = 0;
  39427. _this.INSTANCES = false;
  39428. _this.GLOSSINESS = false;
  39429. _this.ROUGHNESS = false;
  39430. _this.EMISSIVEASILLUMINATION = false;
  39431. _this.LINKEMISSIVEWITHDIFFUSE = false;
  39432. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  39433. _this.LIGHTMAP = false;
  39434. _this.LIGHTMAPDIRECTUV = 0;
  39435. _this.OBJECTSPACE_NORMALMAP = false;
  39436. _this.USELIGHTMAPASSHADOWMAP = false;
  39437. _this.REFLECTIONMAP_3D = false;
  39438. _this.REFLECTIONMAP_SPHERICAL = false;
  39439. _this.REFLECTIONMAP_PLANAR = false;
  39440. _this.REFLECTIONMAP_CUBIC = false;
  39441. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  39442. _this.REFLECTIONMAP_PROJECTION = false;
  39443. _this.REFLECTIONMAP_SKYBOX = false;
  39444. _this.REFLECTIONMAP_EXPLICIT = false;
  39445. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  39446. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  39447. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  39448. _this.INVERTCUBICMAP = false;
  39449. _this.LOGARITHMICDEPTH = false;
  39450. _this.REFRACTION = false;
  39451. _this.REFRACTIONMAP_3D = false;
  39452. _this.REFLECTIONOVERALPHA = false;
  39453. _this.TWOSIDEDLIGHTING = false;
  39454. _this.SHADOWFLOAT = false;
  39455. _this.MORPHTARGETS = false;
  39456. _this.MORPHTARGETS_NORMAL = false;
  39457. _this.MORPHTARGETS_TANGENT = false;
  39458. _this.NUM_MORPH_INFLUENCERS = 0;
  39459. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  39460. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  39461. _this.IMAGEPROCESSING = false;
  39462. _this.VIGNETTE = false;
  39463. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  39464. _this.VIGNETTEBLENDMODEOPAQUE = false;
  39465. _this.TONEMAPPING = false;
  39466. _this.CONTRAST = false;
  39467. _this.COLORCURVES = false;
  39468. _this.COLORGRADING = false;
  39469. _this.COLORGRADING3D = false;
  39470. _this.SAMPLER3DGREENDEPTH = false;
  39471. _this.SAMPLER3DBGRMAP = false;
  39472. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  39473. _this.EXPOSURE = false;
  39474. _this.GRAIN = false;
  39475. _this.rebuild();
  39476. return _this;
  39477. }
  39478. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  39479. var modes = [
  39480. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  39481. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  39482. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  39483. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  39484. ];
  39485. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  39486. var mode = modes_1[_i];
  39487. this[mode] = (mode === modeToEnable);
  39488. }
  39489. };
  39490. return StandardMaterialDefines;
  39491. }(BABYLON.MaterialDefines));
  39492. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  39493. var StandardMaterial = /** @class */ (function (_super) {
  39494. __extends(StandardMaterial, _super);
  39495. function StandardMaterial(name, scene) {
  39496. var _this = _super.call(this, name, scene) || this;
  39497. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  39498. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  39499. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  39500. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  39501. _this.specularPower = 64;
  39502. _this._useAlphaFromDiffuseTexture = false;
  39503. _this._useEmissiveAsIllumination = false;
  39504. _this._linkEmissiveWithDiffuse = false;
  39505. _this._useSpecularOverAlpha = false;
  39506. _this._useReflectionOverAlpha = false;
  39507. _this._disableLighting = false;
  39508. _this._useObjectSpaceNormalMap = false;
  39509. _this._useParallax = false;
  39510. _this._useParallaxOcclusion = false;
  39511. _this.parallaxScaleBias = 0.05;
  39512. _this._roughness = 0;
  39513. _this.indexOfRefraction = 0.98;
  39514. _this.invertRefractionY = true;
  39515. _this._useLightmapAsShadowmap = false;
  39516. _this._useReflectionFresnelFromSpecular = false;
  39517. _this._useGlossinessFromSpecularMapAlpha = false;
  39518. _this._maxSimultaneousLights = 4;
  39519. /**
  39520. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  39521. */
  39522. _this._invertNormalMapX = false;
  39523. /**
  39524. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  39525. */
  39526. _this._invertNormalMapY = false;
  39527. /**
  39528. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  39529. */
  39530. _this._twoSidedLighting = false;
  39531. _this._renderTargets = new BABYLON.SmartArray(16);
  39532. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  39533. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  39534. // Setup the default processing configuration to the scene.
  39535. _this._attachImageProcessingConfiguration(null);
  39536. _this.getRenderTargetTextures = function () {
  39537. _this._renderTargets.reset();
  39538. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  39539. _this._renderTargets.push(_this._reflectionTexture);
  39540. }
  39541. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  39542. _this._renderTargets.push(_this._refractionTexture);
  39543. }
  39544. return _this._renderTargets;
  39545. };
  39546. return _this;
  39547. }
  39548. ;
  39549. ;
  39550. ;
  39551. ;
  39552. ;
  39553. ;
  39554. ;
  39555. ;
  39556. ;
  39557. ;
  39558. ;
  39559. ;
  39560. ;
  39561. ;
  39562. ;
  39563. ;
  39564. ;
  39565. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  39566. /**
  39567. * Gets the image processing configuration used either in this material.
  39568. */
  39569. get: function () {
  39570. return this._imageProcessingConfiguration;
  39571. },
  39572. /**
  39573. * Sets the Default image processing configuration used either in the this material.
  39574. *
  39575. * If sets to null, the scene one is in use.
  39576. */
  39577. set: function (value) {
  39578. this._attachImageProcessingConfiguration(value);
  39579. // Ensure the effect will be rebuilt.
  39580. this._markAllSubMeshesAsTexturesDirty();
  39581. },
  39582. enumerable: true,
  39583. configurable: true
  39584. });
  39585. /**
  39586. * Attaches a new image processing configuration to the Standard Material.
  39587. * @param configuration
  39588. */
  39589. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  39590. var _this = this;
  39591. if (configuration === this._imageProcessingConfiguration) {
  39592. return;
  39593. }
  39594. // Detaches observer.
  39595. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  39596. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  39597. }
  39598. // Pick the scene configuration if needed.
  39599. if (!configuration) {
  39600. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  39601. }
  39602. else {
  39603. this._imageProcessingConfiguration = configuration;
  39604. }
  39605. // Attaches observer.
  39606. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  39607. _this._markAllSubMeshesAsImageProcessingDirty();
  39608. });
  39609. };
  39610. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  39611. /**
  39612. * Gets wether the color curves effect is enabled.
  39613. */
  39614. get: function () {
  39615. return this.imageProcessingConfiguration.colorCurvesEnabled;
  39616. },
  39617. /**
  39618. * Sets wether the color curves effect is enabled.
  39619. */
  39620. set: function (value) {
  39621. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  39622. },
  39623. enumerable: true,
  39624. configurable: true
  39625. });
  39626. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  39627. /**
  39628. * Gets wether the color grading effect is enabled.
  39629. */
  39630. get: function () {
  39631. return this.imageProcessingConfiguration.colorGradingEnabled;
  39632. },
  39633. /**
  39634. * Gets wether the color grading effect is enabled.
  39635. */
  39636. set: function (value) {
  39637. this.imageProcessingConfiguration.colorGradingEnabled = value;
  39638. },
  39639. enumerable: true,
  39640. configurable: true
  39641. });
  39642. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  39643. /**
  39644. * Gets wether tonemapping is enabled or not.
  39645. */
  39646. get: function () {
  39647. return this._imageProcessingConfiguration.toneMappingEnabled;
  39648. },
  39649. /**
  39650. * Sets wether tonemapping is enabled or not
  39651. */
  39652. set: function (value) {
  39653. this._imageProcessingConfiguration.toneMappingEnabled = value;
  39654. },
  39655. enumerable: true,
  39656. configurable: true
  39657. });
  39658. ;
  39659. ;
  39660. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  39661. /**
  39662. * The camera exposure used on this material.
  39663. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39664. * This corresponds to a photographic exposure.
  39665. */
  39666. get: function () {
  39667. return this._imageProcessingConfiguration.exposure;
  39668. },
  39669. /**
  39670. * The camera exposure used on this material.
  39671. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  39672. * This corresponds to a photographic exposure.
  39673. */
  39674. set: function (value) {
  39675. this._imageProcessingConfiguration.exposure = value;
  39676. },
  39677. enumerable: true,
  39678. configurable: true
  39679. });
  39680. ;
  39681. ;
  39682. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  39683. /**
  39684. * Gets The camera contrast used on this material.
  39685. */
  39686. get: function () {
  39687. return this._imageProcessingConfiguration.contrast;
  39688. },
  39689. /**
  39690. * Sets The camera contrast used on this material.
  39691. */
  39692. set: function (value) {
  39693. this._imageProcessingConfiguration.contrast = value;
  39694. },
  39695. enumerable: true,
  39696. configurable: true
  39697. });
  39698. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  39699. /**
  39700. * Gets the Color Grading 2D Lookup Texture.
  39701. */
  39702. get: function () {
  39703. return this._imageProcessingConfiguration.colorGradingTexture;
  39704. },
  39705. /**
  39706. * Sets the Color Grading 2D Lookup Texture.
  39707. */
  39708. set: function (value) {
  39709. this._imageProcessingConfiguration.colorGradingTexture = value;
  39710. },
  39711. enumerable: true,
  39712. configurable: true
  39713. });
  39714. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  39715. /**
  39716. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39717. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39718. * 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;
  39719. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39720. */
  39721. get: function () {
  39722. return this._imageProcessingConfiguration.colorCurves;
  39723. },
  39724. /**
  39725. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  39726. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  39727. * 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;
  39728. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  39729. */
  39730. set: function (value) {
  39731. this._imageProcessingConfiguration.colorCurves = value;
  39732. },
  39733. enumerable: true,
  39734. configurable: true
  39735. });
  39736. StandardMaterial.prototype.getClassName = function () {
  39737. return "StandardMaterial";
  39738. };
  39739. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  39740. get: function () {
  39741. return this._useLogarithmicDepth;
  39742. },
  39743. set: function (value) {
  39744. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  39745. this._markAllSubMeshesAsMiscDirty();
  39746. },
  39747. enumerable: true,
  39748. configurable: true
  39749. });
  39750. StandardMaterial.prototype.needAlphaBlending = function () {
  39751. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  39752. };
  39753. StandardMaterial.prototype.needAlphaTesting = function () {
  39754. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  39755. };
  39756. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  39757. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  39758. };
  39759. StandardMaterial.prototype.getAlphaTestTexture = function () {
  39760. return this._diffuseTexture;
  39761. };
  39762. /**
  39763. * Child classes can use it to update shaders
  39764. */
  39765. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  39766. if (useInstances === void 0) { useInstances = false; }
  39767. if (subMesh.effect && this.isFrozen) {
  39768. if (this._wasPreviouslyReady && subMesh.effect) {
  39769. return true;
  39770. }
  39771. }
  39772. if (!subMesh._materialDefines) {
  39773. subMesh._materialDefines = new StandardMaterialDefines();
  39774. }
  39775. var scene = this.getScene();
  39776. var defines = subMesh._materialDefines;
  39777. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  39778. if (defines._renderId === scene.getRenderId()) {
  39779. return true;
  39780. }
  39781. }
  39782. var engine = scene.getEngine();
  39783. // Lights
  39784. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  39785. // Textures
  39786. if (defines._areTexturesDirty) {
  39787. defines._needUVs = false;
  39788. defines.MAINUV1 = false;
  39789. defines.MAINUV2 = false;
  39790. if (scene.texturesEnabled) {
  39791. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  39792. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  39793. return false;
  39794. }
  39795. else {
  39796. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  39797. }
  39798. }
  39799. else {
  39800. defines.DIFFUSE = false;
  39801. }
  39802. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  39803. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  39804. return false;
  39805. }
  39806. else {
  39807. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  39808. }
  39809. }
  39810. else {
  39811. defines.AMBIENT = false;
  39812. }
  39813. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  39814. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  39815. return false;
  39816. }
  39817. else {
  39818. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  39819. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  39820. }
  39821. }
  39822. else {
  39823. defines.OPACITY = false;
  39824. }
  39825. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  39826. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  39827. return false;
  39828. }
  39829. else {
  39830. defines._needNormals = true;
  39831. defines.REFLECTION = true;
  39832. defines.ROUGHNESS = (this._roughness > 0);
  39833. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  39834. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  39835. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  39836. switch (this._reflectionTexture.coordinatesMode) {
  39837. case BABYLON.Texture.CUBIC_MODE:
  39838. case BABYLON.Texture.INVCUBIC_MODE:
  39839. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  39840. break;
  39841. case BABYLON.Texture.EXPLICIT_MODE:
  39842. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  39843. break;
  39844. case BABYLON.Texture.PLANAR_MODE:
  39845. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  39846. break;
  39847. case BABYLON.Texture.PROJECTION_MODE:
  39848. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  39849. break;
  39850. case BABYLON.Texture.SKYBOX_MODE:
  39851. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  39852. break;
  39853. case BABYLON.Texture.SPHERICAL_MODE:
  39854. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  39855. break;
  39856. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  39857. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  39858. break;
  39859. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  39860. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  39861. break;
  39862. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  39863. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  39864. break;
  39865. }
  39866. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  39867. }
  39868. }
  39869. else {
  39870. defines.REFLECTION = false;
  39871. }
  39872. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  39873. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  39874. return false;
  39875. }
  39876. else {
  39877. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  39878. }
  39879. }
  39880. else {
  39881. defines.EMISSIVE = false;
  39882. }
  39883. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  39884. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  39885. return false;
  39886. }
  39887. else {
  39888. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  39889. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  39890. }
  39891. }
  39892. else {
  39893. defines.LIGHTMAP = false;
  39894. }
  39895. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  39896. if (!this._specularTexture.isReadyOrNotBlocking()) {
  39897. return false;
  39898. }
  39899. else {
  39900. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  39901. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  39902. }
  39903. }
  39904. else {
  39905. defines.SPECULAR = false;
  39906. }
  39907. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  39908. // Bump texure can not be not blocking.
  39909. if (!this._bumpTexture.isReady()) {
  39910. return false;
  39911. }
  39912. else {
  39913. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  39914. defines.PARALLAX = this._useParallax;
  39915. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  39916. }
  39917. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  39918. }
  39919. else {
  39920. defines.BUMP = false;
  39921. }
  39922. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  39923. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  39924. return false;
  39925. }
  39926. else {
  39927. defines._needUVs = true;
  39928. defines.REFRACTION = true;
  39929. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  39930. }
  39931. }
  39932. else {
  39933. defines.REFRACTION = false;
  39934. }
  39935. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  39936. }
  39937. else {
  39938. defines.DIFFUSE = false;
  39939. defines.AMBIENT = false;
  39940. defines.OPACITY = false;
  39941. defines.REFLECTION = false;
  39942. defines.EMISSIVE = false;
  39943. defines.LIGHTMAP = false;
  39944. defines.BUMP = false;
  39945. defines.REFRACTION = false;
  39946. }
  39947. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  39948. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  39949. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  39950. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  39951. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  39952. }
  39953. if (defines._areImageProcessingDirty) {
  39954. if (!this._imageProcessingConfiguration.isReady()) {
  39955. return false;
  39956. }
  39957. this._imageProcessingConfiguration.prepareDefines(defines);
  39958. }
  39959. if (defines._areFresnelDirty) {
  39960. if (StandardMaterial.FresnelEnabled) {
  39961. // Fresnel
  39962. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  39963. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  39964. this._reflectionFresnelParameters) {
  39965. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  39966. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  39967. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  39968. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  39969. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  39970. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  39971. defines._needNormals = true;
  39972. defines.FRESNEL = true;
  39973. }
  39974. }
  39975. else {
  39976. defines.FRESNEL = false;
  39977. }
  39978. }
  39979. // Misc.
  39980. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  39981. // Attribs
  39982. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  39983. // Values that need to be evaluated on every frame
  39984. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  39985. // Get correct effect
  39986. if (defines.isDirty) {
  39987. defines.markAsProcessed();
  39988. scene.resetCachedMaterial();
  39989. // Fallbacks
  39990. var fallbacks = new BABYLON.EffectFallbacks();
  39991. if (defines.REFLECTION) {
  39992. fallbacks.addFallback(0, "REFLECTION");
  39993. }
  39994. if (defines.SPECULAR) {
  39995. fallbacks.addFallback(0, "SPECULAR");
  39996. }
  39997. if (defines.BUMP) {
  39998. fallbacks.addFallback(0, "BUMP");
  39999. }
  40000. if (defines.PARALLAX) {
  40001. fallbacks.addFallback(1, "PARALLAX");
  40002. }
  40003. if (defines.PARALLAXOCCLUSION) {
  40004. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  40005. }
  40006. if (defines.SPECULAROVERALPHA) {
  40007. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  40008. }
  40009. if (defines.FOG) {
  40010. fallbacks.addFallback(1, "FOG");
  40011. }
  40012. if (defines.POINTSIZE) {
  40013. fallbacks.addFallback(0, "POINTSIZE");
  40014. }
  40015. if (defines.LOGARITHMICDEPTH) {
  40016. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  40017. }
  40018. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  40019. if (defines.SPECULARTERM) {
  40020. fallbacks.addFallback(0, "SPECULARTERM");
  40021. }
  40022. if (defines.DIFFUSEFRESNEL) {
  40023. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  40024. }
  40025. if (defines.OPACITYFRESNEL) {
  40026. fallbacks.addFallback(2, "OPACITYFRESNEL");
  40027. }
  40028. if (defines.REFLECTIONFRESNEL) {
  40029. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  40030. }
  40031. if (defines.EMISSIVEFRESNEL) {
  40032. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  40033. }
  40034. if (defines.FRESNEL) {
  40035. fallbacks.addFallback(4, "FRESNEL");
  40036. }
  40037. //Attributes
  40038. var attribs = [BABYLON.VertexBuffer.PositionKind];
  40039. if (defines.NORMAL) {
  40040. attribs.push(BABYLON.VertexBuffer.NormalKind);
  40041. }
  40042. if (defines.UV1) {
  40043. attribs.push(BABYLON.VertexBuffer.UVKind);
  40044. }
  40045. if (defines.UV2) {
  40046. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  40047. }
  40048. if (defines.VERTEXCOLOR) {
  40049. attribs.push(BABYLON.VertexBuffer.ColorKind);
  40050. }
  40051. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  40052. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  40053. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  40054. var shaderName = "default";
  40055. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  40056. "vFogInfos", "vFogColor", "pointSize",
  40057. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  40058. "mBones",
  40059. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  40060. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  40061. "vReflectionPosition", "vReflectionSize",
  40062. "logarithmicDepthConstant", "vTangentSpaceParams"
  40063. ];
  40064. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  40065. var uniformBuffers = ["Material", "Scene"];
  40066. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  40067. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  40068. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  40069. uniformsNames: uniforms,
  40070. uniformBuffersNames: uniformBuffers,
  40071. samplers: samplers,
  40072. defines: defines,
  40073. maxSimultaneousLights: this._maxSimultaneousLights
  40074. });
  40075. if (this.customShaderNameResolve) {
  40076. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  40077. }
  40078. var join = defines.toString();
  40079. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  40080. attributes: attribs,
  40081. uniformsNames: uniforms,
  40082. uniformBuffersNames: uniformBuffers,
  40083. samplers: samplers,
  40084. defines: join,
  40085. fallbacks: fallbacks,
  40086. onCompiled: this.onCompiled,
  40087. onError: this.onError,
  40088. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  40089. }, engine), defines);
  40090. this.buildUniformLayout();
  40091. }
  40092. if (!subMesh.effect || !subMesh.effect.isReady()) {
  40093. return false;
  40094. }
  40095. defines._renderId = scene.getRenderId();
  40096. this._wasPreviouslyReady = true;
  40097. return true;
  40098. };
  40099. StandardMaterial.prototype.buildUniformLayout = function () {
  40100. // Order is important !
  40101. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  40102. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  40103. this._uniformBuffer.addUniform("opacityParts", 4);
  40104. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  40105. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  40106. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  40107. this._uniformBuffer.addUniform("refractionRightColor", 4);
  40108. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  40109. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  40110. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  40111. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  40112. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  40113. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  40114. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  40115. this._uniformBuffer.addUniform("vReflectionSize", 3);
  40116. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  40117. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  40118. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  40119. this._uniformBuffer.addUniform("vBumpInfos", 3);
  40120. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  40121. this._uniformBuffer.addUniform("ambientMatrix", 16);
  40122. this._uniformBuffer.addUniform("opacityMatrix", 16);
  40123. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  40124. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  40125. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  40126. this._uniformBuffer.addUniform("specularMatrix", 16);
  40127. this._uniformBuffer.addUniform("bumpMatrix", 16);
  40128. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  40129. this._uniformBuffer.addUniform("refractionMatrix", 16);
  40130. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  40131. this._uniformBuffer.addUniform("vSpecularColor", 4);
  40132. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  40133. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  40134. this._uniformBuffer.addUniform("pointSize", 1);
  40135. this._uniformBuffer.create();
  40136. };
  40137. StandardMaterial.prototype.unbind = function () {
  40138. if (this._activeEffect) {
  40139. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  40140. this._activeEffect.setTexture("reflection2DSampler", null);
  40141. }
  40142. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  40143. this._activeEffect.setTexture("refraction2DSampler", null);
  40144. }
  40145. }
  40146. _super.prototype.unbind.call(this);
  40147. };
  40148. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  40149. var scene = this.getScene();
  40150. var defines = subMesh._materialDefines;
  40151. if (!defines) {
  40152. return;
  40153. }
  40154. var effect = subMesh.effect;
  40155. if (!effect) {
  40156. return;
  40157. }
  40158. this._activeEffect = effect;
  40159. // Matrices
  40160. this.bindOnlyWorldMatrix(world);
  40161. // Normal Matrix
  40162. if (defines.OBJECTSPACE_NORMALMAP) {
  40163. world.toNormalMatrix(this._normalMatrix);
  40164. this.bindOnlyNormalMatrix(this._normalMatrix);
  40165. }
  40166. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  40167. // Bones
  40168. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  40169. if (mustRebind) {
  40170. this._uniformBuffer.bindToEffect(effect, "Material");
  40171. this.bindViewProjection(effect);
  40172. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  40173. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  40174. // Fresnel
  40175. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  40176. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  40177. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  40178. }
  40179. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  40180. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  40181. }
  40182. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  40183. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  40184. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  40185. }
  40186. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  40187. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  40188. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  40189. }
  40190. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  40191. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  40192. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  40193. }
  40194. }
  40195. // Textures
  40196. if (scene.texturesEnabled) {
  40197. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  40198. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  40199. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  40200. }
  40201. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  40202. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  40203. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  40204. }
  40205. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  40206. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  40207. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  40208. }
  40209. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  40210. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  40211. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  40212. if (this._reflectionTexture.boundingBoxSize) {
  40213. var cubeTexture = this._reflectionTexture;
  40214. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  40215. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  40216. }
  40217. }
  40218. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  40219. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  40220. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  40221. }
  40222. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  40223. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  40224. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  40225. }
  40226. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  40227. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  40228. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  40229. }
  40230. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  40231. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  40232. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  40233. if (scene._mirroredCameraPosition) {
  40234. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  40235. }
  40236. else {
  40237. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  40238. }
  40239. }
  40240. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  40241. var depth = 1.0;
  40242. if (!this._refractionTexture.isCube) {
  40243. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  40244. if (this._refractionTexture.depth) {
  40245. depth = this._refractionTexture.depth;
  40246. }
  40247. }
  40248. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  40249. }
  40250. }
  40251. // Point size
  40252. if (this.pointsCloud) {
  40253. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  40254. }
  40255. if (defines.SPECULARTERM) {
  40256. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  40257. }
  40258. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  40259. // Diffuse
  40260. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  40261. }
  40262. // Textures
  40263. if (scene.texturesEnabled) {
  40264. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  40265. effect.setTexture("diffuseSampler", this._diffuseTexture);
  40266. }
  40267. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  40268. effect.setTexture("ambientSampler", this._ambientTexture);
  40269. }
  40270. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  40271. effect.setTexture("opacitySampler", this._opacityTexture);
  40272. }
  40273. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  40274. if (this._reflectionTexture.isCube) {
  40275. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  40276. }
  40277. else {
  40278. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  40279. }
  40280. }
  40281. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  40282. effect.setTexture("emissiveSampler", this._emissiveTexture);
  40283. }
  40284. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  40285. effect.setTexture("lightmapSampler", this._lightmapTexture);
  40286. }
  40287. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  40288. effect.setTexture("specularSampler", this._specularTexture);
  40289. }
  40290. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  40291. effect.setTexture("bumpSampler", this._bumpTexture);
  40292. }
  40293. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  40294. var depth = 1.0;
  40295. if (this._refractionTexture.isCube) {
  40296. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  40297. }
  40298. else {
  40299. effect.setTexture("refraction2DSampler", this._refractionTexture);
  40300. }
  40301. }
  40302. }
  40303. // Clip plane
  40304. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  40305. // Colors
  40306. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  40307. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  40308. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  40309. }
  40310. if (mustRebind || !this.isFrozen) {
  40311. // Lights
  40312. if (scene.lightsEnabled && !this._disableLighting) {
  40313. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  40314. }
  40315. // View
  40316. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  40317. this.bindView(effect);
  40318. }
  40319. // Fog
  40320. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  40321. // Morph targets
  40322. if (defines.NUM_MORPH_INFLUENCERS) {
  40323. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  40324. }
  40325. // Log. depth
  40326. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  40327. // image processing
  40328. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  40329. this._imageProcessingConfiguration.bind(this._activeEffect);
  40330. }
  40331. }
  40332. this._uniformBuffer.update();
  40333. this._afterBind(mesh, this._activeEffect);
  40334. };
  40335. StandardMaterial.prototype.getAnimatables = function () {
  40336. var results = [];
  40337. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  40338. results.push(this._diffuseTexture);
  40339. }
  40340. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  40341. results.push(this._ambientTexture);
  40342. }
  40343. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  40344. results.push(this._opacityTexture);
  40345. }
  40346. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  40347. results.push(this._reflectionTexture);
  40348. }
  40349. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  40350. results.push(this._emissiveTexture);
  40351. }
  40352. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  40353. results.push(this._specularTexture);
  40354. }
  40355. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  40356. results.push(this._bumpTexture);
  40357. }
  40358. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  40359. results.push(this._lightmapTexture);
  40360. }
  40361. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  40362. results.push(this._refractionTexture);
  40363. }
  40364. return results;
  40365. };
  40366. StandardMaterial.prototype.getActiveTextures = function () {
  40367. var activeTextures = _super.prototype.getActiveTextures.call(this);
  40368. if (this._diffuseTexture) {
  40369. activeTextures.push(this._diffuseTexture);
  40370. }
  40371. if (this._ambientTexture) {
  40372. activeTextures.push(this._ambientTexture);
  40373. }
  40374. if (this._opacityTexture) {
  40375. activeTextures.push(this._opacityTexture);
  40376. }
  40377. if (this._reflectionTexture) {
  40378. activeTextures.push(this._reflectionTexture);
  40379. }
  40380. if (this._emissiveTexture) {
  40381. activeTextures.push(this._emissiveTexture);
  40382. }
  40383. if (this._specularTexture) {
  40384. activeTextures.push(this._specularTexture);
  40385. }
  40386. if (this._bumpTexture) {
  40387. activeTextures.push(this._bumpTexture);
  40388. }
  40389. if (this._lightmapTexture) {
  40390. activeTextures.push(this._lightmapTexture);
  40391. }
  40392. if (this._refractionTexture) {
  40393. activeTextures.push(this._refractionTexture);
  40394. }
  40395. return activeTextures;
  40396. };
  40397. StandardMaterial.prototype.hasTexture = function (texture) {
  40398. if (_super.prototype.hasTexture.call(this, texture)) {
  40399. return true;
  40400. }
  40401. if (this._diffuseTexture === texture) {
  40402. return true;
  40403. }
  40404. if (this._ambientTexture === texture) {
  40405. return true;
  40406. }
  40407. if (this._opacityTexture === texture) {
  40408. return true;
  40409. }
  40410. if (this._reflectionTexture === texture) {
  40411. return true;
  40412. }
  40413. if (this._emissiveTexture === texture) {
  40414. return true;
  40415. }
  40416. if (this._specularTexture === texture) {
  40417. return true;
  40418. }
  40419. if (this._bumpTexture === texture) {
  40420. return true;
  40421. }
  40422. if (this._lightmapTexture === texture) {
  40423. return true;
  40424. }
  40425. if (this._refractionTexture === texture) {
  40426. return true;
  40427. }
  40428. return false;
  40429. };
  40430. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  40431. if (forceDisposeTextures) {
  40432. if (this._diffuseTexture) {
  40433. this._diffuseTexture.dispose();
  40434. }
  40435. if (this._ambientTexture) {
  40436. this._ambientTexture.dispose();
  40437. }
  40438. if (this._opacityTexture) {
  40439. this._opacityTexture.dispose();
  40440. }
  40441. if (this._reflectionTexture) {
  40442. this._reflectionTexture.dispose();
  40443. }
  40444. if (this._emissiveTexture) {
  40445. this._emissiveTexture.dispose();
  40446. }
  40447. if (this._specularTexture) {
  40448. this._specularTexture.dispose();
  40449. }
  40450. if (this._bumpTexture) {
  40451. this._bumpTexture.dispose();
  40452. }
  40453. if (this._lightmapTexture) {
  40454. this._lightmapTexture.dispose();
  40455. }
  40456. if (this._refractionTexture) {
  40457. this._refractionTexture.dispose();
  40458. }
  40459. }
  40460. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  40461. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  40462. }
  40463. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  40464. };
  40465. StandardMaterial.prototype.clone = function (name) {
  40466. var _this = this;
  40467. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  40468. result.name = name;
  40469. result.id = name;
  40470. return result;
  40471. };
  40472. StandardMaterial.prototype.serialize = function () {
  40473. return BABYLON.SerializationHelper.Serialize(this);
  40474. };
  40475. // Statics
  40476. StandardMaterial.Parse = function (source, scene, rootUrl) {
  40477. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  40478. };
  40479. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  40480. get: function () {
  40481. return StandardMaterial._DiffuseTextureEnabled;
  40482. },
  40483. set: function (value) {
  40484. if (StandardMaterial._DiffuseTextureEnabled === value) {
  40485. return;
  40486. }
  40487. StandardMaterial._DiffuseTextureEnabled = value;
  40488. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40489. },
  40490. enumerable: true,
  40491. configurable: true
  40492. });
  40493. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  40494. get: function () {
  40495. return StandardMaterial._AmbientTextureEnabled;
  40496. },
  40497. set: function (value) {
  40498. if (StandardMaterial._AmbientTextureEnabled === value) {
  40499. return;
  40500. }
  40501. StandardMaterial._AmbientTextureEnabled = value;
  40502. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40503. },
  40504. enumerable: true,
  40505. configurable: true
  40506. });
  40507. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  40508. get: function () {
  40509. return StandardMaterial._OpacityTextureEnabled;
  40510. },
  40511. set: function (value) {
  40512. if (StandardMaterial._OpacityTextureEnabled === value) {
  40513. return;
  40514. }
  40515. StandardMaterial._OpacityTextureEnabled = value;
  40516. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40517. },
  40518. enumerable: true,
  40519. configurable: true
  40520. });
  40521. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  40522. get: function () {
  40523. return StandardMaterial._ReflectionTextureEnabled;
  40524. },
  40525. set: function (value) {
  40526. if (StandardMaterial._ReflectionTextureEnabled === value) {
  40527. return;
  40528. }
  40529. StandardMaterial._ReflectionTextureEnabled = value;
  40530. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40531. },
  40532. enumerable: true,
  40533. configurable: true
  40534. });
  40535. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  40536. get: function () {
  40537. return StandardMaterial._EmissiveTextureEnabled;
  40538. },
  40539. set: function (value) {
  40540. if (StandardMaterial._EmissiveTextureEnabled === value) {
  40541. return;
  40542. }
  40543. StandardMaterial._EmissiveTextureEnabled = value;
  40544. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40545. },
  40546. enumerable: true,
  40547. configurable: true
  40548. });
  40549. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  40550. get: function () {
  40551. return StandardMaterial._SpecularTextureEnabled;
  40552. },
  40553. set: function (value) {
  40554. if (StandardMaterial._SpecularTextureEnabled === value) {
  40555. return;
  40556. }
  40557. StandardMaterial._SpecularTextureEnabled = value;
  40558. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40559. },
  40560. enumerable: true,
  40561. configurable: true
  40562. });
  40563. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  40564. get: function () {
  40565. return StandardMaterial._BumpTextureEnabled;
  40566. },
  40567. set: function (value) {
  40568. if (StandardMaterial._BumpTextureEnabled === value) {
  40569. return;
  40570. }
  40571. StandardMaterial._BumpTextureEnabled = value;
  40572. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40573. },
  40574. enumerable: true,
  40575. configurable: true
  40576. });
  40577. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  40578. get: function () {
  40579. return StandardMaterial._LightmapTextureEnabled;
  40580. },
  40581. set: function (value) {
  40582. if (StandardMaterial._LightmapTextureEnabled === value) {
  40583. return;
  40584. }
  40585. StandardMaterial._LightmapTextureEnabled = value;
  40586. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40587. },
  40588. enumerable: true,
  40589. configurable: true
  40590. });
  40591. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  40592. get: function () {
  40593. return StandardMaterial._RefractionTextureEnabled;
  40594. },
  40595. set: function (value) {
  40596. if (StandardMaterial._RefractionTextureEnabled === value) {
  40597. return;
  40598. }
  40599. StandardMaterial._RefractionTextureEnabled = value;
  40600. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40601. },
  40602. enumerable: true,
  40603. configurable: true
  40604. });
  40605. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  40606. get: function () {
  40607. return StandardMaterial._ColorGradingTextureEnabled;
  40608. },
  40609. set: function (value) {
  40610. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  40611. return;
  40612. }
  40613. StandardMaterial._ColorGradingTextureEnabled = value;
  40614. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  40615. },
  40616. enumerable: true,
  40617. configurable: true
  40618. });
  40619. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  40620. get: function () {
  40621. return StandardMaterial._FresnelEnabled;
  40622. },
  40623. set: function (value) {
  40624. if (StandardMaterial._FresnelEnabled === value) {
  40625. return;
  40626. }
  40627. StandardMaterial._FresnelEnabled = value;
  40628. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  40629. },
  40630. enumerable: true,
  40631. configurable: true
  40632. });
  40633. // Flags used to enable or disable a type of texture for all Standard Materials
  40634. StandardMaterial._DiffuseTextureEnabled = true;
  40635. StandardMaterial._AmbientTextureEnabled = true;
  40636. StandardMaterial._OpacityTextureEnabled = true;
  40637. StandardMaterial._ReflectionTextureEnabled = true;
  40638. StandardMaterial._EmissiveTextureEnabled = true;
  40639. StandardMaterial._SpecularTextureEnabled = true;
  40640. StandardMaterial._BumpTextureEnabled = true;
  40641. StandardMaterial._LightmapTextureEnabled = true;
  40642. StandardMaterial._RefractionTextureEnabled = true;
  40643. StandardMaterial._ColorGradingTextureEnabled = true;
  40644. StandardMaterial._FresnelEnabled = true;
  40645. __decorate([
  40646. BABYLON.serializeAsTexture("diffuseTexture")
  40647. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  40648. __decorate([
  40649. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40650. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  40651. __decorate([
  40652. BABYLON.serializeAsTexture("ambientTexture")
  40653. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  40654. __decorate([
  40655. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40656. ], StandardMaterial.prototype, "ambientTexture", void 0);
  40657. __decorate([
  40658. BABYLON.serializeAsTexture("opacityTexture")
  40659. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  40660. __decorate([
  40661. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  40662. ], StandardMaterial.prototype, "opacityTexture", void 0);
  40663. __decorate([
  40664. BABYLON.serializeAsTexture("reflectionTexture")
  40665. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  40666. __decorate([
  40667. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40668. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  40669. __decorate([
  40670. BABYLON.serializeAsTexture("emissiveTexture")
  40671. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  40672. __decorate([
  40673. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40674. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  40675. __decorate([
  40676. BABYLON.serializeAsTexture("specularTexture")
  40677. ], StandardMaterial.prototype, "_specularTexture", void 0);
  40678. __decorate([
  40679. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40680. ], StandardMaterial.prototype, "specularTexture", void 0);
  40681. __decorate([
  40682. BABYLON.serializeAsTexture("bumpTexture")
  40683. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  40684. __decorate([
  40685. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40686. ], StandardMaterial.prototype, "bumpTexture", void 0);
  40687. __decorate([
  40688. BABYLON.serializeAsTexture("lightmapTexture")
  40689. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  40690. __decorate([
  40691. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40692. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  40693. __decorate([
  40694. BABYLON.serializeAsTexture("refractionTexture")
  40695. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  40696. __decorate([
  40697. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40698. ], StandardMaterial.prototype, "refractionTexture", void 0);
  40699. __decorate([
  40700. BABYLON.serializeAsColor3("ambient")
  40701. ], StandardMaterial.prototype, "ambientColor", void 0);
  40702. __decorate([
  40703. BABYLON.serializeAsColor3("diffuse")
  40704. ], StandardMaterial.prototype, "diffuseColor", void 0);
  40705. __decorate([
  40706. BABYLON.serializeAsColor3("specular")
  40707. ], StandardMaterial.prototype, "specularColor", void 0);
  40708. __decorate([
  40709. BABYLON.serializeAsColor3("emissive")
  40710. ], StandardMaterial.prototype, "emissiveColor", void 0);
  40711. __decorate([
  40712. BABYLON.serialize()
  40713. ], StandardMaterial.prototype, "specularPower", void 0);
  40714. __decorate([
  40715. BABYLON.serialize("useAlphaFromDiffuseTexture")
  40716. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  40717. __decorate([
  40718. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40719. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  40720. __decorate([
  40721. BABYLON.serialize("useEmissiveAsIllumination")
  40722. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  40723. __decorate([
  40724. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40725. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  40726. __decorate([
  40727. BABYLON.serialize("linkEmissiveWithDiffuse")
  40728. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  40729. __decorate([
  40730. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40731. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  40732. __decorate([
  40733. BABYLON.serialize("useSpecularOverAlpha")
  40734. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  40735. __decorate([
  40736. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40737. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  40738. __decorate([
  40739. BABYLON.serialize("useReflectionOverAlpha")
  40740. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  40741. __decorate([
  40742. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40743. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  40744. __decorate([
  40745. BABYLON.serialize("disableLighting")
  40746. ], StandardMaterial.prototype, "_disableLighting", void 0);
  40747. __decorate([
  40748. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40749. ], StandardMaterial.prototype, "disableLighting", void 0);
  40750. __decorate([
  40751. BABYLON.serialize("useObjectSpaceNormalMap")
  40752. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  40753. __decorate([
  40754. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40755. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  40756. __decorate([
  40757. BABYLON.serialize("useParallax")
  40758. ], StandardMaterial.prototype, "_useParallax", void 0);
  40759. __decorate([
  40760. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40761. ], StandardMaterial.prototype, "useParallax", void 0);
  40762. __decorate([
  40763. BABYLON.serialize("useParallaxOcclusion")
  40764. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  40765. __decorate([
  40766. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40767. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  40768. __decorate([
  40769. BABYLON.serialize()
  40770. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  40771. __decorate([
  40772. BABYLON.serialize("roughness")
  40773. ], StandardMaterial.prototype, "_roughness", void 0);
  40774. __decorate([
  40775. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40776. ], StandardMaterial.prototype, "roughness", void 0);
  40777. __decorate([
  40778. BABYLON.serialize()
  40779. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  40780. __decorate([
  40781. BABYLON.serialize()
  40782. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  40783. __decorate([
  40784. BABYLON.serialize("useLightmapAsShadowmap")
  40785. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  40786. __decorate([
  40787. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40788. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  40789. __decorate([
  40790. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  40791. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  40792. __decorate([
  40793. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40794. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  40795. __decorate([
  40796. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  40797. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  40798. __decorate([
  40799. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  40800. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  40801. __decorate([
  40802. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  40803. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  40804. __decorate([
  40805. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40806. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  40807. __decorate([
  40808. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  40809. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  40810. __decorate([
  40811. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40812. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  40813. __decorate([
  40814. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  40815. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  40816. __decorate([
  40817. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40818. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  40819. __decorate([
  40820. BABYLON.serialize("useReflectionFresnelFromSpecular")
  40821. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  40822. __decorate([
  40823. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  40824. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  40825. __decorate([
  40826. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  40827. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  40828. __decorate([
  40829. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40830. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  40831. __decorate([
  40832. BABYLON.serialize("maxSimultaneousLights")
  40833. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  40834. __decorate([
  40835. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  40836. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  40837. __decorate([
  40838. BABYLON.serialize("invertNormalMapX")
  40839. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  40840. __decorate([
  40841. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40842. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  40843. __decorate([
  40844. BABYLON.serialize("invertNormalMapY")
  40845. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  40846. __decorate([
  40847. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40848. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  40849. __decorate([
  40850. BABYLON.serialize("twoSidedLighting")
  40851. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  40852. __decorate([
  40853. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  40854. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  40855. __decorate([
  40856. BABYLON.serialize()
  40857. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  40858. return StandardMaterial;
  40859. }(BABYLON.PushMaterial));
  40860. BABYLON.StandardMaterial = StandardMaterial;
  40861. })(BABYLON || (BABYLON = {}));
  40862. //# sourceMappingURL=babylon.standardMaterial.js.map
  40863. "use strict";
  40864. var BABYLON;
  40865. (function (BABYLON) {
  40866. /**
  40867. * Manages the defines for the PBR Material.
  40868. */
  40869. var PBRMaterialDefines = /** @class */ (function (_super) {
  40870. __extends(PBRMaterialDefines, _super);
  40871. /**
  40872. * Initializes the PBR Material defines.
  40873. */
  40874. function PBRMaterialDefines() {
  40875. var _this = _super.call(this) || this;
  40876. _this.PBR = true;
  40877. _this.MAINUV1 = false;
  40878. _this.MAINUV2 = false;
  40879. _this.UV1 = false;
  40880. _this.UV2 = false;
  40881. _this.ALBEDO = false;
  40882. _this.ALBEDODIRECTUV = 0;
  40883. _this.VERTEXCOLOR = false;
  40884. _this.AMBIENT = false;
  40885. _this.AMBIENTDIRECTUV = 0;
  40886. _this.AMBIENTINGRAYSCALE = false;
  40887. _this.OPACITY = false;
  40888. _this.VERTEXALPHA = false;
  40889. _this.OPACITYDIRECTUV = 0;
  40890. _this.OPACITYRGB = false;
  40891. _this.ALPHATEST = false;
  40892. _this.DEPTHPREPASS = false;
  40893. _this.ALPHABLEND = false;
  40894. _this.ALPHAFROMALBEDO = false;
  40895. _this.ALPHATESTVALUE = "0.5";
  40896. _this.SPECULAROVERALPHA = false;
  40897. _this.RADIANCEOVERALPHA = false;
  40898. _this.ALPHAFRESNEL = false;
  40899. _this.LINEARALPHAFRESNEL = false;
  40900. _this.PREMULTIPLYALPHA = false;
  40901. _this.EMISSIVE = false;
  40902. _this.EMISSIVEDIRECTUV = 0;
  40903. _this.REFLECTIVITY = false;
  40904. _this.REFLECTIVITYDIRECTUV = 0;
  40905. _this.SPECULARTERM = false;
  40906. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  40907. _this.MICROSURFACEAUTOMATIC = false;
  40908. _this.LODBASEDMICROSFURACE = false;
  40909. _this.MICROSURFACEMAP = false;
  40910. _this.MICROSURFACEMAPDIRECTUV = 0;
  40911. _this.METALLICWORKFLOW = false;
  40912. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  40913. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  40914. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  40915. _this.AOSTOREINMETALMAPRED = false;
  40916. _this.ENVIRONMENTBRDF = false;
  40917. _this.NORMAL = false;
  40918. _this.TANGENT = false;
  40919. _this.BUMP = false;
  40920. _this.BUMPDIRECTUV = 0;
  40921. _this.OBJECTSPACE_NORMALMAP = false;
  40922. _this.PARALLAX = false;
  40923. _this.PARALLAXOCCLUSION = false;
  40924. _this.NORMALXYSCALE = true;
  40925. _this.LIGHTMAP = false;
  40926. _this.LIGHTMAPDIRECTUV = 0;
  40927. _this.USELIGHTMAPASSHADOWMAP = false;
  40928. _this.GAMMALIGHTMAP = false;
  40929. _this.REFLECTION = false;
  40930. _this.REFLECTIONMAP_3D = false;
  40931. _this.REFLECTIONMAP_SPHERICAL = false;
  40932. _this.REFLECTIONMAP_PLANAR = false;
  40933. _this.REFLECTIONMAP_CUBIC = false;
  40934. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  40935. _this.REFLECTIONMAP_PROJECTION = false;
  40936. _this.REFLECTIONMAP_SKYBOX = false;
  40937. _this.REFLECTIONMAP_EXPLICIT = false;
  40938. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  40939. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  40940. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  40941. _this.INVERTCUBICMAP = false;
  40942. _this.USESPHERICALFROMREFLECTIONMAP = false;
  40943. _this.USESPHERICALINVERTEX = false;
  40944. _this.REFLECTIONMAP_OPPOSITEZ = false;
  40945. _this.LODINREFLECTIONALPHA = false;
  40946. _this.GAMMAREFLECTION = false;
  40947. _this.RADIANCEOCCLUSION = false;
  40948. _this.HORIZONOCCLUSION = false;
  40949. _this.REFRACTION = false;
  40950. _this.REFRACTIONMAP_3D = false;
  40951. _this.REFRACTIONMAP_OPPOSITEZ = false;
  40952. _this.LODINREFRACTIONALPHA = false;
  40953. _this.GAMMAREFRACTION = false;
  40954. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  40955. _this.INSTANCES = false;
  40956. _this.NUM_BONE_INFLUENCERS = 0;
  40957. _this.BonesPerMesh = 0;
  40958. _this.NONUNIFORMSCALING = false;
  40959. _this.MORPHTARGETS = false;
  40960. _this.MORPHTARGETS_NORMAL = false;
  40961. _this.MORPHTARGETS_TANGENT = false;
  40962. _this.NUM_MORPH_INFLUENCERS = 0;
  40963. _this.IMAGEPROCESSING = false;
  40964. _this.VIGNETTE = false;
  40965. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  40966. _this.VIGNETTEBLENDMODEOPAQUE = false;
  40967. _this.TONEMAPPING = false;
  40968. _this.CONTRAST = false;
  40969. _this.COLORCURVES = false;
  40970. _this.COLORGRADING = false;
  40971. _this.COLORGRADING3D = false;
  40972. _this.SAMPLER3DGREENDEPTH = false;
  40973. _this.SAMPLER3DBGRMAP = false;
  40974. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  40975. _this.EXPOSURE = false;
  40976. _this.GRAIN = false;
  40977. _this.USEPHYSICALLIGHTFALLOFF = false;
  40978. _this.TWOSIDEDLIGHTING = false;
  40979. _this.SHADOWFLOAT = false;
  40980. _this.CLIPPLANE = false;
  40981. _this.POINTSIZE = false;
  40982. _this.FOG = false;
  40983. _this.LOGARITHMICDEPTH = false;
  40984. _this.FORCENORMALFORWARD = false;
  40985. _this.UNLIT = false;
  40986. _this.rebuild();
  40987. return _this;
  40988. }
  40989. /**
  40990. * Resets the PBR Material defines.
  40991. */
  40992. PBRMaterialDefines.prototype.reset = function () {
  40993. _super.prototype.reset.call(this);
  40994. this.ALPHATESTVALUE = "0.5";
  40995. this.PBR = true;
  40996. };
  40997. return PBRMaterialDefines;
  40998. }(BABYLON.MaterialDefines));
  40999. /**
  41000. * The Physically based material base class of BJS.
  41001. *
  41002. * This offers the main features of a standard PBR material.
  41003. * For more information, please refer to the documentation :
  41004. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  41005. */
  41006. var PBRBaseMaterial = /** @class */ (function (_super) {
  41007. __extends(PBRBaseMaterial, _super);
  41008. /**
  41009. * Instantiates a new PBRMaterial instance.
  41010. *
  41011. * @param name The material name
  41012. * @param scene The scene the material will be use in.
  41013. */
  41014. function PBRBaseMaterial(name, scene) {
  41015. var _this = _super.call(this, name, scene) || this;
  41016. /**
  41017. * Intensity of the direct lights e.g. the four lights available in your scene.
  41018. * This impacts both the direct diffuse and specular highlights.
  41019. */
  41020. _this._directIntensity = 1.0;
  41021. /**
  41022. * Intensity of the emissive part of the material.
  41023. * This helps controlling the emissive effect without modifying the emissive color.
  41024. */
  41025. _this._emissiveIntensity = 1.0;
  41026. /**
  41027. * Intensity of the environment e.g. how much the environment will light the object
  41028. * either through harmonics for rough material or through the refelction for shiny ones.
  41029. */
  41030. _this._environmentIntensity = 1.0;
  41031. /**
  41032. * This is a special control allowing the reduction of the specular highlights coming from the
  41033. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  41034. */
  41035. _this._specularIntensity = 1.0;
  41036. /**
  41037. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  41038. */
  41039. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  41040. /**
  41041. * Debug Control allowing disabling the bump map on this material.
  41042. */
  41043. _this._disableBumpMap = false;
  41044. /**
  41045. * AKA Occlusion Texture Intensity in other nomenclature.
  41046. */
  41047. _this._ambientTextureStrength = 1.0;
  41048. /**
  41049. * The color of a material in ambient lighting.
  41050. */
  41051. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  41052. /**
  41053. * AKA Diffuse Color in other nomenclature.
  41054. */
  41055. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  41056. /**
  41057. * AKA Specular Color in other nomenclature.
  41058. */
  41059. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  41060. /**
  41061. * The color applied when light is reflected from a material.
  41062. */
  41063. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  41064. /**
  41065. * The color applied when light is emitted from a material.
  41066. */
  41067. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  41068. /**
  41069. * AKA Glossiness in other nomenclature.
  41070. */
  41071. _this._microSurface = 0.9;
  41072. /**
  41073. * source material index of refraction (IOR)' / 'destination material IOR.
  41074. */
  41075. _this._indexOfRefraction = 0.66;
  41076. /**
  41077. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  41078. */
  41079. _this._invertRefractionY = false;
  41080. /**
  41081. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  41082. * Materials half opaque for instance using refraction could benefit from this control.
  41083. */
  41084. _this._linkRefractionWithTransparency = false;
  41085. /**
  41086. * Specifies that the material will use the light map as a show map.
  41087. */
  41088. _this._useLightmapAsShadowmap = false;
  41089. /**
  41090. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  41091. * makes the reflect vector face the model (under horizon).
  41092. */
  41093. _this._useHorizonOcclusion = true;
  41094. /**
  41095. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  41096. * too much the area relying on ambient texture to define their ambient occlusion.
  41097. */
  41098. _this._useRadianceOcclusion = true;
  41099. /**
  41100. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  41101. */
  41102. _this._useAlphaFromAlbedoTexture = false;
  41103. /**
  41104. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  41105. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  41106. */
  41107. _this._useSpecularOverAlpha = true;
  41108. /**
  41109. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  41110. */
  41111. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  41112. /**
  41113. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  41114. */
  41115. _this._useRoughnessFromMetallicTextureAlpha = true;
  41116. /**
  41117. * Specifies if the metallic texture contains the roughness information in its green channel.
  41118. */
  41119. _this._useRoughnessFromMetallicTextureGreen = false;
  41120. /**
  41121. * Specifies if the metallic texture contains the metallness information in its blue channel.
  41122. */
  41123. _this._useMetallnessFromMetallicTextureBlue = false;
  41124. /**
  41125. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  41126. */
  41127. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  41128. /**
  41129. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  41130. */
  41131. _this._useAmbientInGrayScale = false;
  41132. /**
  41133. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  41134. * The material will try to infer what glossiness each pixel should be.
  41135. */
  41136. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  41137. /**
  41138. * BJS is using an harcoded light falloff based on a manually sets up range.
  41139. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  41140. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  41141. */
  41142. _this._usePhysicalLightFalloff = true;
  41143. /**
  41144. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  41145. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  41146. */
  41147. _this._useRadianceOverAlpha = true;
  41148. /**
  41149. * Allows using an object space normal map (instead of tangent space).
  41150. */
  41151. _this._useObjectSpaceNormalMap = false;
  41152. /**
  41153. * Allows using the bump map in parallax mode.
  41154. */
  41155. _this._useParallax = false;
  41156. /**
  41157. * Allows using the bump map in parallax occlusion mode.
  41158. */
  41159. _this._useParallaxOcclusion = false;
  41160. /**
  41161. * Controls the scale bias of the parallax mode.
  41162. */
  41163. _this._parallaxScaleBias = 0.05;
  41164. /**
  41165. * If sets to true, disables all the lights affecting the material.
  41166. */
  41167. _this._disableLighting = false;
  41168. /**
  41169. * Number of Simultaneous lights allowed on the material.
  41170. */
  41171. _this._maxSimultaneousLights = 4;
  41172. /**
  41173. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  41174. */
  41175. _this._invertNormalMapX = false;
  41176. /**
  41177. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  41178. */
  41179. _this._invertNormalMapY = false;
  41180. /**
  41181. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  41182. */
  41183. _this._twoSidedLighting = false;
  41184. /**
  41185. * Defines the alpha limits in alpha test mode.
  41186. */
  41187. _this._alphaCutOff = 0.4;
  41188. /**
  41189. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  41190. */
  41191. _this._forceAlphaTest = false;
  41192. /**
  41193. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41194. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  41195. */
  41196. _this._useAlphaFresnel = false;
  41197. /**
  41198. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  41199. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  41200. */
  41201. _this._useLinearAlphaFresnel = false;
  41202. /**
  41203. * The transparency mode of the material.
  41204. */
  41205. _this._transparencyMode = null;
  41206. /**
  41207. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  41208. * from cos thetav and roughness:
  41209. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  41210. */
  41211. _this._environmentBRDFTexture = null;
  41212. /**
  41213. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  41214. */
  41215. _this._forceIrradianceInFragment = false;
  41216. /**
  41217. * Force normal to face away from face.
  41218. */
  41219. _this._forceNormalForward = false;
  41220. /**
  41221. * Stores the available render targets.
  41222. */
  41223. _this._renderTargets = new BABYLON.SmartArray(16);
  41224. /**
  41225. * Sets the global ambient color for the material used in lighting calculations.
  41226. */
  41227. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  41228. /**
  41229. * If set to true, no lighting calculations will be applied.
  41230. */
  41231. _this._unlit = false;
  41232. // Setup the default processing configuration to the scene.
  41233. _this._attachImageProcessingConfiguration(null);
  41234. _this.getRenderTargetTextures = function () {
  41235. _this._renderTargets.reset();
  41236. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  41237. _this._renderTargets.push(_this._reflectionTexture);
  41238. }
  41239. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  41240. _this._renderTargets.push(_this._refractionTexture);
  41241. }
  41242. return _this._renderTargets;
  41243. };
  41244. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  41245. return _this;
  41246. }
  41247. /**
  41248. * Attaches a new image processing configuration to the PBR Material.
  41249. * @param configuration
  41250. */
  41251. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  41252. var _this = this;
  41253. if (configuration === this._imageProcessingConfiguration) {
  41254. return;
  41255. }
  41256. // Detaches observer.
  41257. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  41258. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  41259. }
  41260. // Pick the scene configuration if needed.
  41261. if (!configuration) {
  41262. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  41263. }
  41264. else {
  41265. this._imageProcessingConfiguration = configuration;
  41266. }
  41267. // Attaches observer.
  41268. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  41269. _this._markAllSubMeshesAsImageProcessingDirty();
  41270. });
  41271. };
  41272. /**
  41273. * Gets the name of the material class.
  41274. */
  41275. PBRBaseMaterial.prototype.getClassName = function () {
  41276. return "PBRBaseMaterial";
  41277. };
  41278. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  41279. /**
  41280. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  41281. */
  41282. get: function () {
  41283. return this._useLogarithmicDepth;
  41284. },
  41285. /**
  41286. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  41287. */
  41288. set: function (value) {
  41289. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  41290. },
  41291. enumerable: true,
  41292. configurable: true
  41293. });
  41294. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  41295. /**
  41296. * Gets the current transparency mode.
  41297. */
  41298. get: function () {
  41299. return this._transparencyMode;
  41300. },
  41301. /**
  41302. * Sets the transparency mode of the material.
  41303. */
  41304. set: function (value) {
  41305. if (this._transparencyMode === value) {
  41306. return;
  41307. }
  41308. this._transparencyMode = value;
  41309. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  41310. this._markAllSubMeshesAsTexturesAndMiscDirty();
  41311. },
  41312. enumerable: true,
  41313. configurable: true
  41314. });
  41315. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  41316. /**
  41317. * Returns true if alpha blending should be disabled.
  41318. */
  41319. get: function () {
  41320. return (this._linkRefractionWithTransparency ||
  41321. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  41322. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  41323. },
  41324. enumerable: true,
  41325. configurable: true
  41326. });
  41327. /**
  41328. * Specifies whether or not this material should be rendered in alpha blend mode.
  41329. */
  41330. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  41331. if (this._disableAlphaBlending) {
  41332. return false;
  41333. }
  41334. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  41335. };
  41336. /**
  41337. * Specifies if the mesh will require alpha blending.
  41338. * @param mesh - BJS mesh.
  41339. */
  41340. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  41341. if (this._disableAlphaBlending) {
  41342. return false;
  41343. }
  41344. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  41345. };
  41346. /**
  41347. * Specifies whether or not this material should be rendered in alpha test mode.
  41348. */
  41349. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  41350. if (this._forceAlphaTest) {
  41351. return true;
  41352. }
  41353. if (this._linkRefractionWithTransparency) {
  41354. return false;
  41355. }
  41356. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  41357. };
  41358. /**
  41359. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  41360. */
  41361. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  41362. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  41363. };
  41364. /**
  41365. * Gets the texture used for the alpha test.
  41366. */
  41367. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  41368. return this._albedoTexture;
  41369. };
  41370. /**
  41371. * Specifies that the submesh is ready to be used.
  41372. * @param mesh - BJS mesh.
  41373. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  41374. * @param useInstances - Specifies that instances should be used.
  41375. * @returns - boolean indicating that the submesh is ready or not.
  41376. */
  41377. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  41378. if (subMesh.effect && this.isFrozen) {
  41379. if (this._wasPreviouslyReady) {
  41380. return true;
  41381. }
  41382. }
  41383. if (!subMesh._materialDefines) {
  41384. subMesh._materialDefines = new PBRMaterialDefines();
  41385. }
  41386. var defines = subMesh._materialDefines;
  41387. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  41388. if (defines._renderId === this.getScene().getRenderId()) {
  41389. return true;
  41390. }
  41391. }
  41392. var scene = this.getScene();
  41393. var engine = scene.getEngine();
  41394. if (defines._areTexturesDirty) {
  41395. if (scene.texturesEnabled) {
  41396. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41397. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  41398. return false;
  41399. }
  41400. }
  41401. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41402. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  41403. return false;
  41404. }
  41405. }
  41406. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41407. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  41408. return false;
  41409. }
  41410. }
  41411. var reflectionTexture = this._getReflectionTexture();
  41412. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41413. if (!reflectionTexture.isReadyOrNotBlocking()) {
  41414. return false;
  41415. }
  41416. }
  41417. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41418. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  41419. return false;
  41420. }
  41421. }
  41422. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41423. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  41424. return false;
  41425. }
  41426. }
  41427. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41428. if (this._metallicTexture) {
  41429. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  41430. return false;
  41431. }
  41432. }
  41433. else if (this._reflectivityTexture) {
  41434. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  41435. return false;
  41436. }
  41437. }
  41438. if (this._microSurfaceTexture) {
  41439. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  41440. return false;
  41441. }
  41442. }
  41443. }
  41444. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41445. // Bump texture cannot be not blocking.
  41446. if (!this._bumpTexture.isReady()) {
  41447. return false;
  41448. }
  41449. }
  41450. var refractionTexture = this._getRefractionTexture();
  41451. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41452. if (!refractionTexture.isReadyOrNotBlocking()) {
  41453. return false;
  41454. }
  41455. }
  41456. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41457. // This is blocking.
  41458. if (!this._environmentBRDFTexture.isReady()) {
  41459. return false;
  41460. }
  41461. }
  41462. }
  41463. }
  41464. if (defines._areImageProcessingDirty) {
  41465. if (!this._imageProcessingConfiguration.isReady()) {
  41466. return false;
  41467. }
  41468. }
  41469. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  41470. mesh.createNormals(true);
  41471. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  41472. }
  41473. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  41474. if (effect) {
  41475. scene.resetCachedMaterial();
  41476. subMesh.setEffect(effect, defines);
  41477. this.buildUniformLayout();
  41478. }
  41479. if (!subMesh.effect || !subMesh.effect.isReady()) {
  41480. return false;
  41481. }
  41482. defines._renderId = scene.getRenderId();
  41483. this._wasPreviouslyReady = true;
  41484. return true;
  41485. };
  41486. /**
  41487. * Specifies if the material uses metallic roughness workflow.
  41488. * @returns boolean specifiying if the material uses metallic roughness workflow.
  41489. */
  41490. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  41491. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  41492. return true;
  41493. }
  41494. return false;
  41495. };
  41496. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  41497. if (onCompiled === void 0) { onCompiled = null; }
  41498. if (onError === void 0) { onError = null; }
  41499. if (useInstances === void 0) { useInstances = null; }
  41500. if (useClipPlane === void 0) { useClipPlane = null; }
  41501. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  41502. if (!defines.isDirty) {
  41503. return null;
  41504. }
  41505. defines.markAsProcessed();
  41506. var scene = this.getScene();
  41507. var engine = scene.getEngine();
  41508. // Fallbacks
  41509. var fallbacks = new BABYLON.EffectFallbacks();
  41510. var fallbackRank = 0;
  41511. if (defines.USESPHERICALINVERTEX) {
  41512. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  41513. }
  41514. if (defines.FOG) {
  41515. fallbacks.addFallback(fallbackRank, "FOG");
  41516. }
  41517. if (defines.POINTSIZE) {
  41518. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  41519. }
  41520. if (defines.LOGARITHMICDEPTH) {
  41521. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  41522. }
  41523. if (defines.PARALLAX) {
  41524. fallbacks.addFallback(fallbackRank, "PARALLAX");
  41525. }
  41526. if (defines.PARALLAXOCCLUSION) {
  41527. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  41528. }
  41529. if (defines.ENVIRONMENTBRDF) {
  41530. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  41531. }
  41532. if (defines.TANGENT) {
  41533. fallbacks.addFallback(fallbackRank++, "TANGENT");
  41534. }
  41535. if (defines.BUMP) {
  41536. fallbacks.addFallback(fallbackRank++, "BUMP");
  41537. }
  41538. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  41539. if (defines.SPECULARTERM) {
  41540. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  41541. }
  41542. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  41543. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  41544. }
  41545. if (defines.LIGHTMAP) {
  41546. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  41547. }
  41548. if (defines.NORMAL) {
  41549. fallbacks.addFallback(fallbackRank++, "NORMAL");
  41550. }
  41551. if (defines.AMBIENT) {
  41552. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  41553. }
  41554. if (defines.EMISSIVE) {
  41555. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  41556. }
  41557. if (defines.VERTEXCOLOR) {
  41558. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  41559. }
  41560. if (defines.NUM_BONE_INFLUENCERS > 0) {
  41561. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  41562. }
  41563. if (defines.MORPHTARGETS) {
  41564. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  41565. }
  41566. //Attributes
  41567. var attribs = [BABYLON.VertexBuffer.PositionKind];
  41568. if (defines.NORMAL) {
  41569. attribs.push(BABYLON.VertexBuffer.NormalKind);
  41570. }
  41571. if (defines.TANGENT) {
  41572. attribs.push(BABYLON.VertexBuffer.TangentKind);
  41573. }
  41574. if (defines.UV1) {
  41575. attribs.push(BABYLON.VertexBuffer.UVKind);
  41576. }
  41577. if (defines.UV2) {
  41578. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  41579. }
  41580. if (defines.VERTEXCOLOR) {
  41581. attribs.push(BABYLON.VertexBuffer.ColorKind);
  41582. }
  41583. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  41584. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  41585. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  41586. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  41587. "vFogInfos", "vFogColor", "pointSize",
  41588. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  41589. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  41590. "mBones",
  41591. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  41592. "vLightingIntensity",
  41593. "logarithmicDepthConstant",
  41594. "vSphericalX", "vSphericalY", "vSphericalZ",
  41595. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  41596. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  41597. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  41598. "vTangentSpaceParams"
  41599. ];
  41600. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  41601. "bumpSampler", "lightmapSampler", "opacitySampler",
  41602. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  41603. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  41604. "microSurfaceSampler", "environmentBrdfSampler"];
  41605. var uniformBuffers = ["Material", "Scene"];
  41606. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  41607. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  41608. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  41609. uniformsNames: uniforms,
  41610. uniformBuffersNames: uniformBuffers,
  41611. samplers: samplers,
  41612. defines: defines,
  41613. maxSimultaneousLights: this._maxSimultaneousLights
  41614. });
  41615. var join = defines.toString();
  41616. return engine.createEffect("pbr", {
  41617. attributes: attribs,
  41618. uniformsNames: uniforms,
  41619. uniformBuffersNames: uniformBuffers,
  41620. samplers: samplers,
  41621. defines: join,
  41622. fallbacks: fallbacks,
  41623. onCompiled: onCompiled,
  41624. onError: onError,
  41625. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  41626. }, engine);
  41627. };
  41628. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  41629. if (useInstances === void 0) { useInstances = null; }
  41630. if (useClipPlane === void 0) { useClipPlane = null; }
  41631. var scene = this.getScene();
  41632. var engine = scene.getEngine();
  41633. // Lights
  41634. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  41635. defines._needNormals = true;
  41636. // Textures
  41637. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  41638. if (defines._areTexturesDirty) {
  41639. defines._needUVs = false;
  41640. if (scene.texturesEnabled) {
  41641. if (scene.getEngine().getCaps().textureLOD) {
  41642. defines.LODBASEDMICROSFURACE = true;
  41643. }
  41644. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41645. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  41646. }
  41647. else {
  41648. defines.ALBEDO = false;
  41649. }
  41650. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41651. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  41652. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  41653. }
  41654. else {
  41655. defines.AMBIENT = false;
  41656. }
  41657. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41658. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  41659. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  41660. }
  41661. else {
  41662. defines.OPACITY = false;
  41663. }
  41664. var reflectionTexture = this._getReflectionTexture();
  41665. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41666. defines.REFLECTION = true;
  41667. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  41668. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  41669. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  41670. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  41671. defines.INVERTCUBICMAP = true;
  41672. }
  41673. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  41674. switch (reflectionTexture.coordinatesMode) {
  41675. case BABYLON.Texture.CUBIC_MODE:
  41676. case BABYLON.Texture.INVCUBIC_MODE:
  41677. defines.REFLECTIONMAP_CUBIC = true;
  41678. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  41679. break;
  41680. case BABYLON.Texture.EXPLICIT_MODE:
  41681. defines.REFLECTIONMAP_EXPLICIT = true;
  41682. break;
  41683. case BABYLON.Texture.PLANAR_MODE:
  41684. defines.REFLECTIONMAP_PLANAR = true;
  41685. break;
  41686. case BABYLON.Texture.PROJECTION_MODE:
  41687. defines.REFLECTIONMAP_PROJECTION = true;
  41688. break;
  41689. case BABYLON.Texture.SKYBOX_MODE:
  41690. defines.REFLECTIONMAP_SKYBOX = true;
  41691. break;
  41692. case BABYLON.Texture.SPHERICAL_MODE:
  41693. defines.REFLECTIONMAP_SPHERICAL = true;
  41694. break;
  41695. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  41696. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  41697. break;
  41698. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  41699. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  41700. break;
  41701. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  41702. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  41703. break;
  41704. }
  41705. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  41706. if (reflectionTexture.sphericalPolynomial) {
  41707. defines.USESPHERICALFROMREFLECTIONMAP = true;
  41708. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  41709. defines.USESPHERICALINVERTEX = false;
  41710. }
  41711. else {
  41712. defines.USESPHERICALINVERTEX = true;
  41713. }
  41714. }
  41715. }
  41716. }
  41717. else {
  41718. defines.REFLECTION = false;
  41719. defines.REFLECTIONMAP_3D = false;
  41720. defines.REFLECTIONMAP_SPHERICAL = false;
  41721. defines.REFLECTIONMAP_PLANAR = false;
  41722. defines.REFLECTIONMAP_CUBIC = false;
  41723. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  41724. defines.REFLECTIONMAP_PROJECTION = false;
  41725. defines.REFLECTIONMAP_SKYBOX = false;
  41726. defines.REFLECTIONMAP_EXPLICIT = false;
  41727. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  41728. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  41729. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  41730. defines.INVERTCUBICMAP = false;
  41731. defines.USESPHERICALFROMREFLECTIONMAP = false;
  41732. defines.USESPHERICALINVERTEX = false;
  41733. defines.REFLECTIONMAP_OPPOSITEZ = false;
  41734. defines.LODINREFLECTIONALPHA = false;
  41735. defines.GAMMAREFLECTION = false;
  41736. }
  41737. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41738. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  41739. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  41740. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  41741. }
  41742. else {
  41743. defines.LIGHTMAP = false;
  41744. }
  41745. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41746. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  41747. }
  41748. else {
  41749. defines.EMISSIVE = false;
  41750. }
  41751. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  41752. if (this._metallicTexture) {
  41753. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  41754. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  41755. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  41756. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  41757. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  41758. }
  41759. else if (this._reflectivityTexture) {
  41760. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  41761. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  41762. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  41763. }
  41764. else {
  41765. defines.REFLECTIVITY = false;
  41766. }
  41767. if (this._microSurfaceTexture) {
  41768. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  41769. }
  41770. else {
  41771. defines.MICROSURFACEMAP = false;
  41772. }
  41773. }
  41774. else {
  41775. defines.REFLECTIVITY = false;
  41776. defines.MICROSURFACEMAP = false;
  41777. }
  41778. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  41779. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  41780. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41781. defines.PARALLAX = true;
  41782. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  41783. }
  41784. else {
  41785. defines.PARALLAX = false;
  41786. }
  41787. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  41788. }
  41789. else {
  41790. defines.BUMP = false;
  41791. }
  41792. var refractionTexture = this._getRefractionTexture();
  41793. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  41794. defines.REFRACTION = true;
  41795. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  41796. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  41797. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  41798. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  41799. if (this._linkRefractionWithTransparency) {
  41800. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  41801. }
  41802. }
  41803. else {
  41804. defines.REFRACTION = false;
  41805. }
  41806. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41807. defines.ENVIRONMENTBRDF = true;
  41808. }
  41809. else {
  41810. defines.ENVIRONMENTBRDF = false;
  41811. }
  41812. if (this._shouldUseAlphaFromAlbedoTexture()) {
  41813. defines.ALPHAFROMALBEDO = true;
  41814. }
  41815. else {
  41816. defines.ALPHAFROMALBEDO = false;
  41817. }
  41818. }
  41819. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  41820. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  41821. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  41822. if (!this.backFaceCulling && this._twoSidedLighting) {
  41823. defines.TWOSIDEDLIGHTING = true;
  41824. }
  41825. else {
  41826. defines.TWOSIDEDLIGHTING = false;
  41827. }
  41828. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  41829. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  41830. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  41831. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  41832. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  41833. }
  41834. if (defines._areImageProcessingDirty) {
  41835. this._imageProcessingConfiguration.prepareDefines(defines);
  41836. }
  41837. defines.FORCENORMALFORWARD = this._forceNormalForward;
  41838. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  41839. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  41840. // Misc.
  41841. if (defines._areMiscDirty) {
  41842. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  41843. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41844. }
  41845. // Values that need to be evaluated on every frame
  41846. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  41847. // Attribs
  41848. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  41849. };
  41850. /**
  41851. * Force shader compilation
  41852. */
  41853. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  41854. var _this = this;
  41855. var localOptions = __assign({ clipPlane: false }, options);
  41856. var defines = new PBRMaterialDefines();
  41857. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  41858. if (effect.isReady()) {
  41859. if (onCompiled) {
  41860. onCompiled(this);
  41861. }
  41862. }
  41863. else {
  41864. effect.onCompileObservable.add(function () {
  41865. if (onCompiled) {
  41866. onCompiled(_this);
  41867. }
  41868. });
  41869. }
  41870. };
  41871. /**
  41872. * Initializes the uniform buffer layout for the shader.
  41873. */
  41874. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  41875. // Order is important !
  41876. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  41877. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  41878. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  41879. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  41880. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  41881. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  41882. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  41883. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  41884. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  41885. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  41886. this._uniformBuffer.addUniform("vReflectionSize", 3);
  41887. this._uniformBuffer.addUniform("vBumpInfos", 3);
  41888. this._uniformBuffer.addUniform("albedoMatrix", 16);
  41889. this._uniformBuffer.addUniform("ambientMatrix", 16);
  41890. this._uniformBuffer.addUniform("opacityMatrix", 16);
  41891. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  41892. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  41893. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  41894. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  41895. this._uniformBuffer.addUniform("bumpMatrix", 16);
  41896. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  41897. this._uniformBuffer.addUniform("refractionMatrix", 16);
  41898. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  41899. this._uniformBuffer.addUniform("vReflectionColor", 3);
  41900. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  41901. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  41902. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  41903. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  41904. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  41905. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  41906. this._uniformBuffer.addUniform("pointSize", 1);
  41907. this._uniformBuffer.create();
  41908. };
  41909. /**
  41910. * Unbinds the textures.
  41911. */
  41912. PBRBaseMaterial.prototype.unbind = function () {
  41913. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  41914. this._uniformBuffer.setTexture("reflectionSampler", null);
  41915. }
  41916. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  41917. this._uniformBuffer.setTexture("refractionSampler", null);
  41918. }
  41919. _super.prototype.unbind.call(this);
  41920. };
  41921. /**
  41922. * Binds the submesh data.
  41923. * @param world - The world matrix.
  41924. * @param mesh - The BJS mesh.
  41925. * @param subMesh - A submesh of the BJS mesh.
  41926. */
  41927. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  41928. var scene = this.getScene();
  41929. var defines = subMesh._materialDefines;
  41930. if (!defines) {
  41931. return;
  41932. }
  41933. var effect = subMesh.effect;
  41934. if (!effect) {
  41935. return;
  41936. }
  41937. this._activeEffect = effect;
  41938. // Matrices
  41939. this.bindOnlyWorldMatrix(world);
  41940. // Normal Matrix
  41941. if (defines.OBJECTSPACE_NORMALMAP) {
  41942. world.toNormalMatrix(this._normalMatrix);
  41943. this.bindOnlyNormalMatrix(this._normalMatrix);
  41944. }
  41945. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  41946. // Bones
  41947. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  41948. var reflectionTexture = null;
  41949. if (mustRebind) {
  41950. this._uniformBuffer.bindToEffect(effect, "Material");
  41951. this.bindViewProjection(effect);
  41952. reflectionTexture = this._getReflectionTexture();
  41953. var refractionTexture = this._getRefractionTexture();
  41954. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  41955. // Texture uniforms
  41956. if (scene.texturesEnabled) {
  41957. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  41958. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  41959. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  41960. }
  41961. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  41962. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  41963. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  41964. }
  41965. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  41966. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  41967. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  41968. }
  41969. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  41970. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  41971. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  41972. if (reflectionTexture.boundingBoxSize) {
  41973. var cubeTexture = reflectionTexture;
  41974. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  41975. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  41976. }
  41977. var polynomials = reflectionTexture.sphericalPolynomial;
  41978. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  41979. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  41980. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  41981. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  41982. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  41983. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  41984. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  41985. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  41986. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  41987. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  41988. }
  41989. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  41990. }
  41991. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  41992. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  41993. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  41994. }
  41995. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  41996. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  41997. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  41998. }
  41999. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  42000. if (this._metallicTexture) {
  42001. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  42002. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  42003. }
  42004. else if (this._reflectivityTexture) {
  42005. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  42006. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  42007. }
  42008. if (this._microSurfaceTexture) {
  42009. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  42010. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  42011. }
  42012. }
  42013. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  42014. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  42015. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42016. if (scene._mirroredCameraPosition) {
  42017. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42018. }
  42019. else {
  42020. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42021. }
  42022. }
  42023. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  42024. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  42025. var depth = 1.0;
  42026. if (!refractionTexture.isCube) {
  42027. if (refractionTexture.depth) {
  42028. depth = refractionTexture.depth;
  42029. }
  42030. }
  42031. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  42032. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  42033. }
  42034. }
  42035. // Point size
  42036. if (this.pointsCloud) {
  42037. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42038. }
  42039. // Colors
  42040. if (defines.METALLICWORKFLOW) {
  42041. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  42042. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  42043. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  42044. }
  42045. else {
  42046. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  42047. }
  42048. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  42049. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  42050. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  42051. // Misc
  42052. this._lightingInfos.x = this._directIntensity;
  42053. this._lightingInfos.y = this._emissiveIntensity;
  42054. this._lightingInfos.z = this._environmentIntensity;
  42055. this._lightingInfos.w = this._specularIntensity;
  42056. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  42057. }
  42058. // Textures
  42059. if (scene.texturesEnabled) {
  42060. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  42061. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  42062. }
  42063. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  42064. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  42065. }
  42066. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  42067. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  42068. }
  42069. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  42070. if (defines.LODBASEDMICROSFURACE) {
  42071. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  42072. }
  42073. else {
  42074. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  42075. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  42076. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  42077. }
  42078. }
  42079. if (defines.ENVIRONMENTBRDF) {
  42080. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  42081. }
  42082. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  42083. if (defines.LODBASEDMICROSFURACE) {
  42084. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  42085. }
  42086. else {
  42087. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  42088. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  42089. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  42090. }
  42091. }
  42092. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  42093. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  42094. }
  42095. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  42096. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  42097. }
  42098. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  42099. if (this._metallicTexture) {
  42100. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  42101. }
  42102. else if (this._reflectivityTexture) {
  42103. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  42104. }
  42105. if (this._microSurfaceTexture) {
  42106. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  42107. }
  42108. }
  42109. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  42110. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  42111. }
  42112. }
  42113. // Clip plane
  42114. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  42115. // Colors
  42116. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  42117. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  42118. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  42119. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  42120. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42121. }
  42122. if (mustRebind || !this.isFrozen) {
  42123. // Lights
  42124. if (scene.lightsEnabled && !this._disableLighting) {
  42125. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  42126. }
  42127. // View
  42128. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  42129. this.bindView(effect);
  42130. }
  42131. // Fog
  42132. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  42133. // Morph targets
  42134. if (defines.NUM_MORPH_INFLUENCERS) {
  42135. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  42136. }
  42137. // image processing
  42138. this._imageProcessingConfiguration.bind(this._activeEffect);
  42139. // Log. depth
  42140. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  42141. }
  42142. this._uniformBuffer.update();
  42143. this._afterBind(mesh);
  42144. };
  42145. /**
  42146. * Returns the animatable textures.
  42147. * @returns - Array of animatable textures.
  42148. */
  42149. PBRBaseMaterial.prototype.getAnimatables = function () {
  42150. var results = [];
  42151. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  42152. results.push(this._albedoTexture);
  42153. }
  42154. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42155. results.push(this._ambientTexture);
  42156. }
  42157. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42158. results.push(this._opacityTexture);
  42159. }
  42160. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42161. results.push(this._reflectionTexture);
  42162. }
  42163. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42164. results.push(this._emissiveTexture);
  42165. }
  42166. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  42167. results.push(this._metallicTexture);
  42168. }
  42169. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  42170. results.push(this._reflectivityTexture);
  42171. }
  42172. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42173. results.push(this._bumpTexture);
  42174. }
  42175. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42176. results.push(this._lightmapTexture);
  42177. }
  42178. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42179. results.push(this._refractionTexture);
  42180. }
  42181. return results;
  42182. };
  42183. /**
  42184. * Returns the texture used for reflections.
  42185. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  42186. */
  42187. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  42188. if (this._reflectionTexture) {
  42189. return this._reflectionTexture;
  42190. }
  42191. return this.getScene().environmentTexture;
  42192. };
  42193. /**
  42194. * Returns the texture used for refraction or null if none is used.
  42195. * @returns - Refection texture if present. If no refraction texture and refraction
  42196. * is linked with transparency, returns environment texture. Otherwise, returns null.
  42197. */
  42198. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  42199. if (this._refractionTexture) {
  42200. return this._refractionTexture;
  42201. }
  42202. if (this._linkRefractionWithTransparency) {
  42203. return this.getScene().environmentTexture;
  42204. }
  42205. return null;
  42206. };
  42207. /**
  42208. * Disposes the resources of the material.
  42209. * @param forceDisposeEffect - Forces the disposal of effects.
  42210. * @param forceDisposeTextures - Forces the disposal of all textures.
  42211. */
  42212. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42213. if (forceDisposeTextures) {
  42214. if (this._albedoTexture) {
  42215. this._albedoTexture.dispose();
  42216. }
  42217. if (this._ambientTexture) {
  42218. this._ambientTexture.dispose();
  42219. }
  42220. if (this._opacityTexture) {
  42221. this._opacityTexture.dispose();
  42222. }
  42223. if (this._reflectionTexture) {
  42224. this._reflectionTexture.dispose();
  42225. }
  42226. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  42227. this._environmentBRDFTexture.dispose();
  42228. }
  42229. if (this._emissiveTexture) {
  42230. this._emissiveTexture.dispose();
  42231. }
  42232. if (this._metallicTexture) {
  42233. this._metallicTexture.dispose();
  42234. }
  42235. if (this._reflectivityTexture) {
  42236. this._reflectivityTexture.dispose();
  42237. }
  42238. if (this._bumpTexture) {
  42239. this._bumpTexture.dispose();
  42240. }
  42241. if (this._lightmapTexture) {
  42242. this._lightmapTexture.dispose();
  42243. }
  42244. if (this._refractionTexture) {
  42245. this._refractionTexture.dispose();
  42246. }
  42247. }
  42248. this._renderTargets.dispose();
  42249. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42250. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42251. }
  42252. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42253. };
  42254. /**
  42255. * Stores the reflectivity values based on metallic roughness workflow.
  42256. */
  42257. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  42258. __decorate([
  42259. BABYLON.serializeAsImageProcessingConfiguration()
  42260. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  42261. __decorate([
  42262. BABYLON.serialize()
  42263. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  42264. __decorate([
  42265. BABYLON.serialize()
  42266. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  42267. return PBRBaseMaterial;
  42268. }(BABYLON.PushMaterial));
  42269. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  42270. })(BABYLON || (BABYLON = {}));
  42271. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  42272. "use strict";
  42273. var BABYLON;
  42274. (function (BABYLON) {
  42275. /**
  42276. * The Physically based simple base material of BJS.
  42277. *
  42278. * This enables better naming and convention enforcements on top of the pbrMaterial.
  42279. * It is used as the base class for both the specGloss and metalRough conventions.
  42280. */
  42281. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  42282. __extends(PBRBaseSimpleMaterial, _super);
  42283. /**
  42284. * Instantiates a new PBRMaterial instance.
  42285. *
  42286. * @param name The material name
  42287. * @param scene The scene the material will be use in.
  42288. */
  42289. function PBRBaseSimpleMaterial(name, scene) {
  42290. var _this = _super.call(this, name, scene) || this;
  42291. /**
  42292. * Number of Simultaneous lights allowed on the material.
  42293. */
  42294. _this.maxSimultaneousLights = 4;
  42295. /**
  42296. * If sets to true, disables all the lights affecting the material.
  42297. */
  42298. _this.disableLighting = false;
  42299. /**
  42300. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42301. */
  42302. _this.invertNormalMapX = false;
  42303. /**
  42304. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42305. */
  42306. _this.invertNormalMapY = false;
  42307. /**
  42308. * Emissivie color used to self-illuminate the model.
  42309. */
  42310. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42311. /**
  42312. * Occlusion Channel Strenght.
  42313. */
  42314. _this.occlusionStrength = 1.0;
  42315. _this.useLightmapAsShadowmap = false;
  42316. _this._useAlphaFromAlbedoTexture = true;
  42317. _this._useAmbientInGrayScale = true;
  42318. return _this;
  42319. }
  42320. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  42321. /**
  42322. * Gets the current double sided mode.
  42323. */
  42324. get: function () {
  42325. return this._twoSidedLighting;
  42326. },
  42327. /**
  42328. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42329. */
  42330. set: function (value) {
  42331. if (this._twoSidedLighting === value) {
  42332. return;
  42333. }
  42334. this._twoSidedLighting = value;
  42335. this.backFaceCulling = !value;
  42336. this._markAllSubMeshesAsTexturesDirty();
  42337. },
  42338. enumerable: true,
  42339. configurable: true
  42340. });
  42341. /**
  42342. * Return the active textures of the material.
  42343. */
  42344. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  42345. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42346. if (this.environmentTexture) {
  42347. activeTextures.push(this.environmentTexture);
  42348. }
  42349. if (this.normalTexture) {
  42350. activeTextures.push(this.normalTexture);
  42351. }
  42352. if (this.emissiveTexture) {
  42353. activeTextures.push(this.emissiveTexture);
  42354. }
  42355. if (this.occlusionTexture) {
  42356. activeTextures.push(this.occlusionTexture);
  42357. }
  42358. if (this.lightmapTexture) {
  42359. activeTextures.push(this.lightmapTexture);
  42360. }
  42361. return activeTextures;
  42362. };
  42363. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  42364. if (_super.prototype.hasTexture.call(this, texture)) {
  42365. return true;
  42366. }
  42367. if (this.lightmapTexture === texture) {
  42368. return true;
  42369. }
  42370. return false;
  42371. };
  42372. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  42373. return "PBRBaseSimpleMaterial";
  42374. };
  42375. __decorate([
  42376. BABYLON.serialize(),
  42377. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42378. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  42379. __decorate([
  42380. BABYLON.serialize(),
  42381. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  42382. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  42383. __decorate([
  42384. BABYLON.serializeAsTexture(),
  42385. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  42386. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  42387. __decorate([
  42388. BABYLON.serialize(),
  42389. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42390. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  42391. __decorate([
  42392. BABYLON.serialize(),
  42393. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42394. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  42395. __decorate([
  42396. BABYLON.serializeAsTexture(),
  42397. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  42398. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  42399. __decorate([
  42400. BABYLON.serializeAsColor3("emissive"),
  42401. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42402. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  42403. __decorate([
  42404. BABYLON.serializeAsTexture(),
  42405. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42406. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  42407. __decorate([
  42408. BABYLON.serialize(),
  42409. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  42410. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  42411. __decorate([
  42412. BABYLON.serializeAsTexture(),
  42413. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  42414. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  42415. __decorate([
  42416. BABYLON.serialize(),
  42417. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  42418. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  42419. __decorate([
  42420. BABYLON.serialize()
  42421. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  42422. __decorate([
  42423. BABYLON.serializeAsTexture(),
  42424. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  42425. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  42426. __decorate([
  42427. BABYLON.serialize(),
  42428. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42429. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  42430. return PBRBaseSimpleMaterial;
  42431. }(BABYLON.PBRBaseMaterial));
  42432. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  42433. })(BABYLON || (BABYLON = {}));
  42434. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  42435. "use strict";
  42436. var BABYLON;
  42437. (function (BABYLON) {
  42438. /**
  42439. * The Physically based material of BJS.
  42440. *
  42441. * This offers the main features of a standard PBR material.
  42442. * For more information, please refer to the documentation :
  42443. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  42444. */
  42445. var PBRMaterial = /** @class */ (function (_super) {
  42446. __extends(PBRMaterial, _super);
  42447. /**
  42448. * Instantiates a new PBRMaterial instance.
  42449. *
  42450. * @param name The material name
  42451. * @param scene The scene the material will be use in.
  42452. */
  42453. function PBRMaterial(name, scene) {
  42454. var _this = _super.call(this, name, scene) || this;
  42455. /**
  42456. * Intensity of the direct lights e.g. the four lights available in your scene.
  42457. * This impacts both the direct diffuse and specular highlights.
  42458. */
  42459. _this.directIntensity = 1.0;
  42460. /**
  42461. * Intensity of the emissive part of the material.
  42462. * This helps controlling the emissive effect without modifying the emissive color.
  42463. */
  42464. _this.emissiveIntensity = 1.0;
  42465. /**
  42466. * Intensity of the environment e.g. how much the environment will light the object
  42467. * either through harmonics for rough material or through the refelction for shiny ones.
  42468. */
  42469. _this.environmentIntensity = 1.0;
  42470. /**
  42471. * This is a special control allowing the reduction of the specular highlights coming from the
  42472. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  42473. */
  42474. _this.specularIntensity = 1.0;
  42475. /**
  42476. * Debug Control allowing disabling the bump map on this material.
  42477. */
  42478. _this.disableBumpMap = false;
  42479. /**
  42480. * AKA Occlusion Texture Intensity in other nomenclature.
  42481. */
  42482. _this.ambientTextureStrength = 1.0;
  42483. /**
  42484. * The color of a material in ambient lighting.
  42485. */
  42486. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42487. /**
  42488. * AKA Diffuse Color in other nomenclature.
  42489. */
  42490. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  42491. /**
  42492. * AKA Specular Color in other nomenclature.
  42493. */
  42494. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  42495. /**
  42496. * The color reflected from the material.
  42497. */
  42498. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  42499. /**
  42500. * The color emitted from the material.
  42501. */
  42502. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42503. /**
  42504. * AKA Glossiness in other nomenclature.
  42505. */
  42506. _this.microSurface = 1.0;
  42507. /**
  42508. * source material index of refraction (IOR)' / 'destination material IOR.
  42509. */
  42510. _this.indexOfRefraction = 0.66;
  42511. /**
  42512. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  42513. */
  42514. _this.invertRefractionY = false;
  42515. /**
  42516. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  42517. * Materials half opaque for instance using refraction could benefit from this control.
  42518. */
  42519. _this.linkRefractionWithTransparency = false;
  42520. _this.useLightmapAsShadowmap = false;
  42521. /**
  42522. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  42523. */
  42524. _this.useAlphaFromAlbedoTexture = false;
  42525. /**
  42526. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  42527. */
  42528. _this.forceAlphaTest = false;
  42529. /**
  42530. * Defines the alpha limits in alpha test mode.
  42531. */
  42532. _this.alphaCutOff = 0.4;
  42533. /**
  42534. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  42535. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  42536. */
  42537. _this.useSpecularOverAlpha = true;
  42538. /**
  42539. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  42540. */
  42541. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  42542. /**
  42543. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  42544. */
  42545. _this.useRoughnessFromMetallicTextureAlpha = true;
  42546. /**
  42547. * Specifies if the metallic texture contains the roughness information in its green channel.
  42548. */
  42549. _this.useRoughnessFromMetallicTextureGreen = false;
  42550. /**
  42551. * Specifies if the metallic texture contains the metallness information in its blue channel.
  42552. */
  42553. _this.useMetallnessFromMetallicTextureBlue = false;
  42554. /**
  42555. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  42556. */
  42557. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  42558. /**
  42559. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  42560. */
  42561. _this.useAmbientInGrayScale = false;
  42562. /**
  42563. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  42564. * The material will try to infer what glossiness each pixel should be.
  42565. */
  42566. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  42567. /**
  42568. * BJS is using an harcoded light falloff based on a manually sets up range.
  42569. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  42570. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  42571. */
  42572. _this.usePhysicalLightFalloff = true;
  42573. /**
  42574. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  42575. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  42576. */
  42577. _this.useRadianceOverAlpha = true;
  42578. /**
  42579. * Allows using an object space normal map (instead of tangent space).
  42580. */
  42581. _this.useObjectSpaceNormalMap = false;
  42582. /**
  42583. * Allows using the bump map in parallax mode.
  42584. */
  42585. _this.useParallax = false;
  42586. /**
  42587. * Allows using the bump map in parallax occlusion mode.
  42588. */
  42589. _this.useParallaxOcclusion = false;
  42590. /**
  42591. * Controls the scale bias of the parallax mode.
  42592. */
  42593. _this.parallaxScaleBias = 0.05;
  42594. /**
  42595. * If sets to true, disables all the lights affecting the material.
  42596. */
  42597. _this.disableLighting = false;
  42598. /**
  42599. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  42600. */
  42601. _this.forceIrradianceInFragment = false;
  42602. /**
  42603. * Number of Simultaneous lights allowed on the material.
  42604. */
  42605. _this.maxSimultaneousLights = 4;
  42606. /**
  42607. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42608. */
  42609. _this.invertNormalMapX = false;
  42610. /**
  42611. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42612. */
  42613. _this.invertNormalMapY = false;
  42614. /**
  42615. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42616. */
  42617. _this.twoSidedLighting = false;
  42618. /**
  42619. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42620. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  42621. */
  42622. _this.useAlphaFresnel = false;
  42623. /**
  42624. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42625. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  42626. */
  42627. _this.useLinearAlphaFresnel = false;
  42628. /**
  42629. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  42630. * And/Or occlude the blended part.
  42631. */
  42632. _this.environmentBRDFTexture = null;
  42633. /**
  42634. * Force normal to face away from face.
  42635. */
  42636. _this.forceNormalForward = false;
  42637. /**
  42638. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  42639. * makes the reflect vector face the model (under horizon).
  42640. */
  42641. _this.useHorizonOcclusion = true;
  42642. /**
  42643. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  42644. * too much the area relying on ambient texture to define their ambient occlusion.
  42645. */
  42646. _this.useRadianceOcclusion = true;
  42647. /**
  42648. * If set to true, no lighting calculations will be applied.
  42649. */
  42650. _this.unlit = false;
  42651. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  42652. return _this;
  42653. }
  42654. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  42655. /**
  42656. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  42657. */
  42658. get: function () {
  42659. return this._PBRMATERIAL_OPAQUE;
  42660. },
  42661. enumerable: true,
  42662. configurable: true
  42663. });
  42664. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  42665. /**
  42666. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42667. */
  42668. get: function () {
  42669. return this._PBRMATERIAL_ALPHATEST;
  42670. },
  42671. enumerable: true,
  42672. configurable: true
  42673. });
  42674. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  42675. /**
  42676. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42677. */
  42678. get: function () {
  42679. return this._PBRMATERIAL_ALPHABLEND;
  42680. },
  42681. enumerable: true,
  42682. configurable: true
  42683. });
  42684. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  42685. /**
  42686. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42687. * They are also discarded below the alpha cutoff threshold to improve performances.
  42688. */
  42689. get: function () {
  42690. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  42691. },
  42692. enumerable: true,
  42693. configurable: true
  42694. });
  42695. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  42696. /**
  42697. * Gets the image processing configuration used either in this material.
  42698. */
  42699. get: function () {
  42700. return this._imageProcessingConfiguration;
  42701. },
  42702. /**
  42703. * Sets the Default image processing configuration used either in the this material.
  42704. *
  42705. * If sets to null, the scene one is in use.
  42706. */
  42707. set: function (value) {
  42708. this._attachImageProcessingConfiguration(value);
  42709. // Ensure the effect will be rebuilt.
  42710. this._markAllSubMeshesAsTexturesDirty();
  42711. },
  42712. enumerable: true,
  42713. configurable: true
  42714. });
  42715. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  42716. /**
  42717. * Gets wether the color curves effect is enabled.
  42718. */
  42719. get: function () {
  42720. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42721. },
  42722. /**
  42723. * Sets wether the color curves effect is enabled.
  42724. */
  42725. set: function (value) {
  42726. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42727. },
  42728. enumerable: true,
  42729. configurable: true
  42730. });
  42731. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  42732. /**
  42733. * Gets wether the color grading effect is enabled.
  42734. */
  42735. get: function () {
  42736. return this.imageProcessingConfiguration.colorGradingEnabled;
  42737. },
  42738. /**
  42739. * Gets wether the color grading effect is enabled.
  42740. */
  42741. set: function (value) {
  42742. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42743. },
  42744. enumerable: true,
  42745. configurable: true
  42746. });
  42747. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  42748. /**
  42749. * Gets wether tonemapping is enabled or not.
  42750. */
  42751. get: function () {
  42752. return this._imageProcessingConfiguration.toneMappingEnabled;
  42753. },
  42754. /**
  42755. * Sets wether tonemapping is enabled or not
  42756. */
  42757. set: function (value) {
  42758. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42759. },
  42760. enumerable: true,
  42761. configurable: true
  42762. });
  42763. ;
  42764. ;
  42765. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  42766. /**
  42767. * The camera exposure used on this material.
  42768. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42769. * This corresponds to a photographic exposure.
  42770. */
  42771. get: function () {
  42772. return this._imageProcessingConfiguration.exposure;
  42773. },
  42774. /**
  42775. * The camera exposure used on this material.
  42776. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42777. * This corresponds to a photographic exposure.
  42778. */
  42779. set: function (value) {
  42780. this._imageProcessingConfiguration.exposure = value;
  42781. },
  42782. enumerable: true,
  42783. configurable: true
  42784. });
  42785. ;
  42786. ;
  42787. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  42788. /**
  42789. * Gets The camera contrast used on this material.
  42790. */
  42791. get: function () {
  42792. return this._imageProcessingConfiguration.contrast;
  42793. },
  42794. /**
  42795. * Sets The camera contrast used on this material.
  42796. */
  42797. set: function (value) {
  42798. this._imageProcessingConfiguration.contrast = value;
  42799. },
  42800. enumerable: true,
  42801. configurable: true
  42802. });
  42803. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  42804. /**
  42805. * Gets the Color Grading 2D Lookup Texture.
  42806. */
  42807. get: function () {
  42808. return this._imageProcessingConfiguration.colorGradingTexture;
  42809. },
  42810. /**
  42811. * Sets the Color Grading 2D Lookup Texture.
  42812. */
  42813. set: function (value) {
  42814. this._imageProcessingConfiguration.colorGradingTexture = value;
  42815. },
  42816. enumerable: true,
  42817. configurable: true
  42818. });
  42819. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  42820. /**
  42821. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42822. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42823. * 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;
  42824. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42825. */
  42826. get: function () {
  42827. return this._imageProcessingConfiguration.colorCurves;
  42828. },
  42829. /**
  42830. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42831. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42832. * 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;
  42833. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42834. */
  42835. set: function (value) {
  42836. this._imageProcessingConfiguration.colorCurves = value;
  42837. },
  42838. enumerable: true,
  42839. configurable: true
  42840. });
  42841. /**
  42842. * Returns the name of this material class.
  42843. */
  42844. PBRMaterial.prototype.getClassName = function () {
  42845. return "PBRMaterial";
  42846. };
  42847. /**
  42848. * Returns an array of the actively used textures.
  42849. * @returns - Array of BaseTextures
  42850. */
  42851. PBRMaterial.prototype.getActiveTextures = function () {
  42852. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42853. if (this._albedoTexture) {
  42854. activeTextures.push(this._albedoTexture);
  42855. }
  42856. if (this._ambientTexture) {
  42857. activeTextures.push(this._ambientTexture);
  42858. }
  42859. if (this._opacityTexture) {
  42860. activeTextures.push(this._opacityTexture);
  42861. }
  42862. if (this._reflectionTexture) {
  42863. activeTextures.push(this._reflectionTexture);
  42864. }
  42865. if (this._emissiveTexture) {
  42866. activeTextures.push(this._emissiveTexture);
  42867. }
  42868. if (this._reflectivityTexture) {
  42869. activeTextures.push(this._reflectivityTexture);
  42870. }
  42871. if (this._metallicTexture) {
  42872. activeTextures.push(this._metallicTexture);
  42873. }
  42874. if (this._microSurfaceTexture) {
  42875. activeTextures.push(this._microSurfaceTexture);
  42876. }
  42877. if (this._bumpTexture) {
  42878. activeTextures.push(this._bumpTexture);
  42879. }
  42880. if (this._lightmapTexture) {
  42881. activeTextures.push(this._lightmapTexture);
  42882. }
  42883. if (this._refractionTexture) {
  42884. activeTextures.push(this._refractionTexture);
  42885. }
  42886. return activeTextures;
  42887. };
  42888. /**
  42889. * Checks to see if a texture is used in the material.
  42890. * @param texture - Base texture to use.
  42891. * @returns - Boolean specifying if a texture is used in the material.
  42892. */
  42893. PBRMaterial.prototype.hasTexture = function (texture) {
  42894. if (_super.prototype.hasTexture.call(this, texture)) {
  42895. return true;
  42896. }
  42897. if (this._albedoTexture === texture) {
  42898. return true;
  42899. }
  42900. if (this._ambientTexture === texture) {
  42901. return true;
  42902. }
  42903. if (this._opacityTexture === texture) {
  42904. return true;
  42905. }
  42906. if (this._reflectionTexture === texture) {
  42907. return true;
  42908. }
  42909. if (this._reflectivityTexture === texture) {
  42910. return true;
  42911. }
  42912. if (this._metallicTexture === texture) {
  42913. return true;
  42914. }
  42915. if (this._microSurfaceTexture === texture) {
  42916. return true;
  42917. }
  42918. if (this._bumpTexture === texture) {
  42919. return true;
  42920. }
  42921. if (this._lightmapTexture === texture) {
  42922. return true;
  42923. }
  42924. if (this._refractionTexture === texture) {
  42925. return true;
  42926. }
  42927. return false;
  42928. };
  42929. /**
  42930. * Makes a duplicate of the current material.
  42931. * @param name - name to use for the new material.
  42932. */
  42933. PBRMaterial.prototype.clone = function (name) {
  42934. var _this = this;
  42935. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  42936. clone.id = name;
  42937. clone.name = name;
  42938. return clone;
  42939. };
  42940. /**
  42941. * Serializes this PBR Material.
  42942. * @returns - An object with the serialized material.
  42943. */
  42944. PBRMaterial.prototype.serialize = function () {
  42945. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42946. serializationObject.customType = "BABYLON.PBRMaterial";
  42947. return serializationObject;
  42948. };
  42949. // Statics
  42950. /**
  42951. * Parses a PBR Material from a serialized object.
  42952. * @param source - Serialized object.
  42953. * @param scene - BJS scene instance.
  42954. * @param rootUrl - url for the scene object
  42955. * @returns - PBRMaterial
  42956. */
  42957. PBRMaterial.Parse = function (source, scene, rootUrl) {
  42958. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  42959. };
  42960. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  42961. /**
  42962. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  42963. */
  42964. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  42965. /**
  42966. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  42967. */
  42968. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  42969. /**
  42970. * 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.
  42971. * They are also discarded below the alpha cutoff threshold to improve performances.
  42972. */
  42973. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  42974. __decorate([
  42975. BABYLON.serialize(),
  42976. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42977. ], PBRMaterial.prototype, "directIntensity", void 0);
  42978. __decorate([
  42979. BABYLON.serialize(),
  42980. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42981. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  42982. __decorate([
  42983. BABYLON.serialize(),
  42984. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42985. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  42986. __decorate([
  42987. BABYLON.serialize(),
  42988. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42989. ], PBRMaterial.prototype, "specularIntensity", void 0);
  42990. __decorate([
  42991. BABYLON.serialize(),
  42992. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42993. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  42994. __decorate([
  42995. BABYLON.serializeAsTexture(),
  42996. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  42997. ], PBRMaterial.prototype, "albedoTexture", void 0);
  42998. __decorate([
  42999. BABYLON.serializeAsTexture(),
  43000. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43001. ], PBRMaterial.prototype, "ambientTexture", void 0);
  43002. __decorate([
  43003. BABYLON.serialize(),
  43004. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43005. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  43006. __decorate([
  43007. BABYLON.serializeAsTexture(),
  43008. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43009. ], PBRMaterial.prototype, "opacityTexture", void 0);
  43010. __decorate([
  43011. BABYLON.serializeAsTexture(),
  43012. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43013. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  43014. __decorate([
  43015. BABYLON.serializeAsTexture(),
  43016. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43017. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  43018. __decorate([
  43019. BABYLON.serializeAsTexture(),
  43020. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43021. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  43022. __decorate([
  43023. BABYLON.serializeAsTexture(),
  43024. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43025. ], PBRMaterial.prototype, "metallicTexture", void 0);
  43026. __decorate([
  43027. BABYLON.serialize(),
  43028. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43029. ], PBRMaterial.prototype, "metallic", void 0);
  43030. __decorate([
  43031. BABYLON.serialize(),
  43032. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43033. ], PBRMaterial.prototype, "roughness", void 0);
  43034. __decorate([
  43035. BABYLON.serializeAsTexture(),
  43036. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43037. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  43038. __decorate([
  43039. BABYLON.serializeAsTexture(),
  43040. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43041. ], PBRMaterial.prototype, "bumpTexture", void 0);
  43042. __decorate([
  43043. BABYLON.serializeAsTexture(),
  43044. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  43045. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  43046. __decorate([
  43047. BABYLON.serializeAsTexture(),
  43048. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43049. ], PBRMaterial.prototype, "refractionTexture", void 0);
  43050. __decorate([
  43051. BABYLON.serializeAsColor3("ambient"),
  43052. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43053. ], PBRMaterial.prototype, "ambientColor", void 0);
  43054. __decorate([
  43055. BABYLON.serializeAsColor3("albedo"),
  43056. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43057. ], PBRMaterial.prototype, "albedoColor", void 0);
  43058. __decorate([
  43059. BABYLON.serializeAsColor3("reflectivity"),
  43060. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43061. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  43062. __decorate([
  43063. BABYLON.serializeAsColor3("reflection"),
  43064. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43065. ], PBRMaterial.prototype, "reflectionColor", void 0);
  43066. __decorate([
  43067. BABYLON.serializeAsColor3("emissive"),
  43068. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43069. ], PBRMaterial.prototype, "emissiveColor", void 0);
  43070. __decorate([
  43071. BABYLON.serialize(),
  43072. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43073. ], PBRMaterial.prototype, "microSurface", void 0);
  43074. __decorate([
  43075. BABYLON.serialize(),
  43076. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43077. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  43078. __decorate([
  43079. BABYLON.serialize(),
  43080. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43081. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  43082. __decorate([
  43083. BABYLON.serialize(),
  43084. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43085. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  43086. __decorate([
  43087. BABYLON.serialize(),
  43088. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43089. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43090. __decorate([
  43091. BABYLON.serialize(),
  43092. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43093. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  43094. __decorate([
  43095. BABYLON.serialize(),
  43096. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43097. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  43098. __decorate([
  43099. BABYLON.serialize(),
  43100. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43101. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  43102. __decorate([
  43103. BABYLON.serialize(),
  43104. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43105. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  43106. __decorate([
  43107. BABYLON.serialize(),
  43108. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43109. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  43110. __decorate([
  43111. BABYLON.serialize(),
  43112. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43113. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  43114. __decorate([
  43115. BABYLON.serialize(),
  43116. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43117. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  43118. __decorate([
  43119. BABYLON.serialize(),
  43120. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43121. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  43122. __decorate([
  43123. BABYLON.serialize(),
  43124. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43125. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  43126. __decorate([
  43127. BABYLON.serialize(),
  43128. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43129. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  43130. __decorate([
  43131. BABYLON.serialize(),
  43132. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43133. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  43134. __decorate([
  43135. BABYLON.serialize(),
  43136. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43137. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  43138. __decorate([
  43139. BABYLON.serialize(),
  43140. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43141. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  43142. __decorate([
  43143. BABYLON.serialize(),
  43144. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43145. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43146. __decorate([
  43147. BABYLON.serialize(),
  43148. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43149. ], PBRMaterial.prototype, "useParallax", void 0);
  43150. __decorate([
  43151. BABYLON.serialize(),
  43152. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43153. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  43154. __decorate([
  43155. BABYLON.serialize(),
  43156. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43157. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  43158. __decorate([
  43159. BABYLON.serialize(),
  43160. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43161. ], PBRMaterial.prototype, "disableLighting", void 0);
  43162. __decorate([
  43163. BABYLON.serialize(),
  43164. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43165. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  43166. __decorate([
  43167. BABYLON.serialize(),
  43168. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43169. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  43170. __decorate([
  43171. BABYLON.serialize(),
  43172. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43173. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  43174. __decorate([
  43175. BABYLON.serialize(),
  43176. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43177. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  43178. __decorate([
  43179. BABYLON.serialize(),
  43180. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43181. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  43182. __decorate([
  43183. BABYLON.serialize(),
  43184. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43185. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  43186. __decorate([
  43187. BABYLON.serialize(),
  43188. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43189. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  43190. __decorate([
  43191. BABYLON.serializeAsTexture(),
  43192. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43193. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  43194. __decorate([
  43195. BABYLON.serialize(),
  43196. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43197. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  43198. __decorate([
  43199. BABYLON.serialize(),
  43200. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43201. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  43202. __decorate([
  43203. BABYLON.serialize(),
  43204. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43205. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  43206. __decorate([
  43207. BABYLON.serialize(),
  43208. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43209. ], PBRMaterial.prototype, "unlit", void 0);
  43210. return PBRMaterial;
  43211. }(BABYLON.PBRBaseMaterial));
  43212. BABYLON.PBRMaterial = PBRMaterial;
  43213. })(BABYLON || (BABYLON = {}));
  43214. //# sourceMappingURL=babylon.pbrMaterial.js.map
  43215. "use strict";
  43216. var BABYLON;
  43217. (function (BABYLON) {
  43218. /**
  43219. * The PBR material of BJS following the metal roughness convention.
  43220. *
  43221. * This fits to the PBR convention in the GLTF definition:
  43222. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  43223. */
  43224. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  43225. __extends(PBRMetallicRoughnessMaterial, _super);
  43226. /**
  43227. * Instantiates a new PBRMetalRoughnessMaterial instance.
  43228. *
  43229. * @param name The material name
  43230. * @param scene The scene the material will be use in.
  43231. */
  43232. function PBRMetallicRoughnessMaterial(name, scene) {
  43233. var _this = _super.call(this, name, scene) || this;
  43234. _this._useRoughnessFromMetallicTextureAlpha = false;
  43235. _this._useRoughnessFromMetallicTextureGreen = true;
  43236. _this._useMetallnessFromMetallicTextureBlue = true;
  43237. _this.metallic = 1.0;
  43238. _this.roughness = 1.0;
  43239. return _this;
  43240. }
  43241. /**
  43242. * Return the currrent class name of the material.
  43243. */
  43244. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  43245. return "PBRMetallicRoughnessMaterial";
  43246. };
  43247. /**
  43248. * Return the active textures of the material.
  43249. */
  43250. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  43251. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43252. if (this.baseTexture) {
  43253. activeTextures.push(this.baseTexture);
  43254. }
  43255. if (this.metallicRoughnessTexture) {
  43256. activeTextures.push(this.metallicRoughnessTexture);
  43257. }
  43258. return activeTextures;
  43259. };
  43260. /**
  43261. * Checks to see if a texture is used in the material.
  43262. * @param texture - Base texture to use.
  43263. * @returns - Boolean specifying if a texture is used in the material.
  43264. */
  43265. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  43266. if (_super.prototype.hasTexture.call(this, texture)) {
  43267. return true;
  43268. }
  43269. if (this.baseTexture === texture) {
  43270. return true;
  43271. }
  43272. if (this.metallicRoughnessTexture === texture) {
  43273. return true;
  43274. }
  43275. return false;
  43276. };
  43277. /**
  43278. * Makes a duplicate of the current material.
  43279. * @param name - name to use for the new material.
  43280. */
  43281. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  43282. var _this = this;
  43283. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  43284. clone.id = name;
  43285. clone.name = name;
  43286. return clone;
  43287. };
  43288. /**
  43289. * Serialize the material to a parsable JSON object.
  43290. */
  43291. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  43292. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43293. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  43294. return serializationObject;
  43295. };
  43296. /**
  43297. * Parses a JSON object correponding to the serialize function.
  43298. */
  43299. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  43300. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  43301. };
  43302. __decorate([
  43303. BABYLON.serializeAsColor3(),
  43304. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  43305. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  43306. __decorate([
  43307. BABYLON.serializeAsTexture(),
  43308. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  43309. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  43310. __decorate([
  43311. BABYLON.serialize(),
  43312. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43313. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  43314. __decorate([
  43315. BABYLON.serialize(),
  43316. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43317. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  43318. __decorate([
  43319. BABYLON.serializeAsTexture(),
  43320. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  43321. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  43322. return PBRMetallicRoughnessMaterial;
  43323. }(BABYLON.PBRBaseSimpleMaterial));
  43324. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  43325. })(BABYLON || (BABYLON = {}));
  43326. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  43327. "use strict";
  43328. var BABYLON;
  43329. (function (BABYLON) {
  43330. /**
  43331. * The PBR material of BJS following the specular glossiness convention.
  43332. *
  43333. * This fits to the PBR convention in the GLTF definition:
  43334. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  43335. */
  43336. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  43337. __extends(PBRSpecularGlossinessMaterial, _super);
  43338. /**
  43339. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  43340. *
  43341. * @param name The material name
  43342. * @param scene The scene the material will be use in.
  43343. */
  43344. function PBRSpecularGlossinessMaterial(name, scene) {
  43345. var _this = _super.call(this, name, scene) || this;
  43346. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  43347. return _this;
  43348. }
  43349. /**
  43350. * Return the currrent class name of the material.
  43351. */
  43352. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  43353. return "PBRSpecularGlossinessMaterial";
  43354. };
  43355. /**
  43356. * Return the active textures of the material.
  43357. */
  43358. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  43359. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43360. if (this.diffuseTexture) {
  43361. activeTextures.push(this.diffuseTexture);
  43362. }
  43363. if (this.specularGlossinessTexture) {
  43364. activeTextures.push(this.specularGlossinessTexture);
  43365. }
  43366. return activeTextures;
  43367. };
  43368. /**
  43369. * Checks to see if a texture is used in the material.
  43370. * @param texture - Base texture to use.
  43371. * @returns - Boolean specifying if a texture is used in the material.
  43372. */
  43373. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  43374. if (_super.prototype.hasTexture.call(this, texture)) {
  43375. return true;
  43376. }
  43377. if (this.diffuseTexture === texture) {
  43378. return true;
  43379. }
  43380. if (this.specularGlossinessTexture === texture) {
  43381. return true;
  43382. }
  43383. return false;
  43384. };
  43385. /**
  43386. * Makes a duplicate of the current material.
  43387. * @param name - name to use for the new material.
  43388. */
  43389. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  43390. var _this = this;
  43391. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  43392. clone.id = name;
  43393. clone.name = name;
  43394. return clone;
  43395. };
  43396. /**
  43397. * Serialize the material to a parsable JSON object.
  43398. */
  43399. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  43400. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  43401. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  43402. return serializationObject;
  43403. };
  43404. /**
  43405. * Parses a JSON object correponding to the serialize function.
  43406. */
  43407. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  43408. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  43409. };
  43410. __decorate([
  43411. BABYLON.serializeAsColor3("diffuse"),
  43412. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  43413. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  43414. __decorate([
  43415. BABYLON.serializeAsTexture(),
  43416. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  43417. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  43418. __decorate([
  43419. BABYLON.serializeAsColor3("specular"),
  43420. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  43421. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  43422. __decorate([
  43423. BABYLON.serialize(),
  43424. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  43425. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  43426. __decorate([
  43427. BABYLON.serializeAsTexture(),
  43428. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  43429. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  43430. return PBRSpecularGlossinessMaterial;
  43431. }(BABYLON.PBRBaseSimpleMaterial));
  43432. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  43433. })(BABYLON || (BABYLON = {}));
  43434. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  43435. "use strict";
  43436. var BABYLON;
  43437. (function (BABYLON) {
  43438. BABYLON.CameraInputTypes = {};
  43439. var CameraInputsManager = /** @class */ (function () {
  43440. function CameraInputsManager(camera) {
  43441. this.attached = {};
  43442. this.camera = camera;
  43443. this.checkInputs = function () { };
  43444. }
  43445. /**
  43446. * Add an input method to a camera.
  43447. * builtin inputs example: camera.inputs.addGamepad();
  43448. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  43449. * @param input camera input method
  43450. */
  43451. CameraInputsManager.prototype.add = function (input) {
  43452. var type = input.getSimpleName();
  43453. if (this.attached[type]) {
  43454. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  43455. return;
  43456. }
  43457. this.attached[type] = input;
  43458. input.camera = this.camera;
  43459. //for checkInputs, we are dynamically creating a function
  43460. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  43461. if (input.checkInputs) {
  43462. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  43463. }
  43464. if (this.attachedElement) {
  43465. input.attachControl(this.attachedElement);
  43466. }
  43467. };
  43468. /**
  43469. * Remove a specific input method from a camera
  43470. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  43471. * @param inputToRemove camera input method
  43472. */
  43473. CameraInputsManager.prototype.remove = function (inputToRemove) {
  43474. for (var cam in this.attached) {
  43475. var input = this.attached[cam];
  43476. if (input === inputToRemove) {
  43477. input.detachControl(this.attachedElement);
  43478. input.camera = null;
  43479. delete this.attached[cam];
  43480. this.rebuildInputCheck();
  43481. }
  43482. }
  43483. };
  43484. CameraInputsManager.prototype.removeByType = function (inputType) {
  43485. for (var cam in this.attached) {
  43486. var input = this.attached[cam];
  43487. if (input.getClassName() === inputType) {
  43488. input.detachControl(this.attachedElement);
  43489. input.camera = null;
  43490. delete this.attached[cam];
  43491. this.rebuildInputCheck();
  43492. }
  43493. }
  43494. };
  43495. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  43496. var current = this.checkInputs;
  43497. return function () {
  43498. current();
  43499. fn();
  43500. };
  43501. };
  43502. CameraInputsManager.prototype.attachInput = function (input) {
  43503. if (this.attachedElement) {
  43504. input.attachControl(this.attachedElement, this.noPreventDefault);
  43505. }
  43506. };
  43507. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  43508. if (noPreventDefault === void 0) { noPreventDefault = false; }
  43509. if (this.attachedElement) {
  43510. return;
  43511. }
  43512. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  43513. this.attachedElement = element;
  43514. this.noPreventDefault = noPreventDefault;
  43515. for (var cam in this.attached) {
  43516. this.attached[cam].attachControl(element, noPreventDefault);
  43517. }
  43518. };
  43519. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  43520. if (disconnect === void 0) { disconnect = false; }
  43521. if (this.attachedElement !== element) {
  43522. return;
  43523. }
  43524. for (var cam in this.attached) {
  43525. this.attached[cam].detachControl(element);
  43526. if (disconnect) {
  43527. this.attached[cam].camera = null;
  43528. }
  43529. }
  43530. this.attachedElement = null;
  43531. };
  43532. CameraInputsManager.prototype.rebuildInputCheck = function () {
  43533. this.checkInputs = function () { };
  43534. for (var cam in this.attached) {
  43535. var input = this.attached[cam];
  43536. if (input.checkInputs) {
  43537. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  43538. }
  43539. }
  43540. };
  43541. /**
  43542. * Remove all attached input methods from a camera
  43543. */
  43544. CameraInputsManager.prototype.clear = function () {
  43545. if (this.attachedElement) {
  43546. this.detachElement(this.attachedElement, true);
  43547. }
  43548. this.attached = {};
  43549. this.attachedElement = null;
  43550. this.checkInputs = function () { };
  43551. };
  43552. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  43553. var inputs = {};
  43554. for (var cam in this.attached) {
  43555. var input = this.attached[cam];
  43556. var res = BABYLON.SerializationHelper.Serialize(input);
  43557. inputs[input.getClassName()] = res;
  43558. }
  43559. serializedCamera.inputsmgr = inputs;
  43560. };
  43561. CameraInputsManager.prototype.parse = function (parsedCamera) {
  43562. var parsedInputs = parsedCamera.inputsmgr;
  43563. if (parsedInputs) {
  43564. this.clear();
  43565. for (var n in parsedInputs) {
  43566. var construct = BABYLON.CameraInputTypes[n];
  43567. if (construct) {
  43568. var parsedinput = parsedInputs[n];
  43569. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  43570. this.add(input);
  43571. }
  43572. }
  43573. }
  43574. else {
  43575. //2016-03-08 this part is for managing backward compatibility
  43576. for (var n in this.attached) {
  43577. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  43578. if (construct) {
  43579. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  43580. this.remove(this.attached[n]);
  43581. this.add(input);
  43582. }
  43583. }
  43584. }
  43585. };
  43586. return CameraInputsManager;
  43587. }());
  43588. BABYLON.CameraInputsManager = CameraInputsManager;
  43589. })(BABYLON || (BABYLON = {}));
  43590. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  43591. "use strict";
  43592. var BABYLON;
  43593. (function (BABYLON) {
  43594. var TargetCamera = /** @class */ (function (_super) {
  43595. __extends(TargetCamera, _super);
  43596. function TargetCamera(name, position, scene) {
  43597. var _this = _super.call(this, name, position, scene) || this;
  43598. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  43599. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  43600. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  43601. _this.speed = 2.0;
  43602. _this.noRotationConstraint = false;
  43603. _this.lockedTarget = null;
  43604. _this._currentTarget = BABYLON.Vector3.Zero();
  43605. _this._viewMatrix = BABYLON.Matrix.Zero();
  43606. _this._camMatrix = BABYLON.Matrix.Zero();
  43607. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  43608. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  43609. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  43610. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  43611. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  43612. _this._lookAtTemp = BABYLON.Matrix.Zero();
  43613. _this._tempMatrix = BABYLON.Matrix.Zero();
  43614. return _this;
  43615. }
  43616. TargetCamera.prototype.getFrontPosition = function (distance) {
  43617. this.getWorldMatrix();
  43618. var direction = this.getTarget().subtract(this.position);
  43619. direction.normalize();
  43620. direction.scaleInPlace(distance);
  43621. return this.globalPosition.add(direction);
  43622. };
  43623. TargetCamera.prototype._getLockedTargetPosition = function () {
  43624. if (!this.lockedTarget) {
  43625. return null;
  43626. }
  43627. if (this.lockedTarget.absolutePosition) {
  43628. this.lockedTarget.computeWorldMatrix();
  43629. }
  43630. return this.lockedTarget.absolutePosition || this.lockedTarget;
  43631. };
  43632. TargetCamera.prototype.storeState = function () {
  43633. this._storedPosition = this.position.clone();
  43634. this._storedRotation = this.rotation.clone();
  43635. if (this.rotationQuaternion) {
  43636. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  43637. }
  43638. return _super.prototype.storeState.call(this);
  43639. };
  43640. /**
  43641. * Restored camera state. You must call storeState() first
  43642. */
  43643. TargetCamera.prototype._restoreStateValues = function () {
  43644. if (!_super.prototype._restoreStateValues.call(this)) {
  43645. return false;
  43646. }
  43647. this.position = this._storedPosition.clone();
  43648. this.rotation = this._storedRotation.clone();
  43649. if (this.rotationQuaternion) {
  43650. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  43651. }
  43652. this.cameraDirection.copyFromFloats(0, 0, 0);
  43653. this.cameraRotation.copyFromFloats(0, 0);
  43654. return true;
  43655. };
  43656. // Cache
  43657. TargetCamera.prototype._initCache = function () {
  43658. _super.prototype._initCache.call(this);
  43659. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43660. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43661. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  43662. };
  43663. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  43664. if (!ignoreParentClass) {
  43665. _super.prototype._updateCache.call(this);
  43666. }
  43667. var lockedTargetPosition = this._getLockedTargetPosition();
  43668. if (!lockedTargetPosition) {
  43669. this._cache.lockedTarget = null;
  43670. }
  43671. else {
  43672. if (!this._cache.lockedTarget) {
  43673. this._cache.lockedTarget = lockedTargetPosition.clone();
  43674. }
  43675. else {
  43676. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  43677. }
  43678. }
  43679. this._cache.rotation.copyFrom(this.rotation);
  43680. if (this.rotationQuaternion)
  43681. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43682. };
  43683. // Synchronized
  43684. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  43685. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  43686. return false;
  43687. }
  43688. var lockedTargetPosition = this._getLockedTargetPosition();
  43689. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  43690. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  43691. };
  43692. // Methods
  43693. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  43694. var engine = this.getEngine();
  43695. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  43696. };
  43697. // Target
  43698. TargetCamera.prototype.setTarget = function (target) {
  43699. this.upVector.normalize();
  43700. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  43701. this._camMatrix.invert();
  43702. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  43703. var vDir = target.subtract(this.position);
  43704. if (vDir.x >= 0.0) {
  43705. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  43706. }
  43707. else {
  43708. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  43709. }
  43710. this.rotation.z = 0;
  43711. if (isNaN(this.rotation.x)) {
  43712. this.rotation.x = 0;
  43713. }
  43714. if (isNaN(this.rotation.y)) {
  43715. this.rotation.y = 0;
  43716. }
  43717. if (isNaN(this.rotation.z)) {
  43718. this.rotation.z = 0;
  43719. }
  43720. if (this.rotationQuaternion) {
  43721. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43722. }
  43723. };
  43724. /**
  43725. * Return the current target position of the camera. This value is expressed in local space.
  43726. */
  43727. TargetCamera.prototype.getTarget = function () {
  43728. return this._currentTarget;
  43729. };
  43730. TargetCamera.prototype._decideIfNeedsToMove = function () {
  43731. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  43732. };
  43733. TargetCamera.prototype._updatePosition = function () {
  43734. if (this.parent) {
  43735. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  43736. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  43737. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  43738. return;
  43739. }
  43740. this.position.addInPlace(this.cameraDirection);
  43741. };
  43742. TargetCamera.prototype._checkInputs = function () {
  43743. var needToMove = this._decideIfNeedsToMove();
  43744. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  43745. // Move
  43746. if (needToMove) {
  43747. this._updatePosition();
  43748. }
  43749. // Rotate
  43750. if (needToRotate) {
  43751. this.rotation.x += this.cameraRotation.x;
  43752. this.rotation.y += this.cameraRotation.y;
  43753. //rotate, if quaternion is set and rotation was used
  43754. if (this.rotationQuaternion) {
  43755. var len = this.rotation.lengthSquared();
  43756. if (len) {
  43757. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  43758. }
  43759. }
  43760. if (!this.noRotationConstraint) {
  43761. var limit = (Math.PI / 2) * 0.95;
  43762. if (this.rotation.x > limit)
  43763. this.rotation.x = limit;
  43764. if (this.rotation.x < -limit)
  43765. this.rotation.x = -limit;
  43766. }
  43767. }
  43768. // Inertia
  43769. if (needToMove) {
  43770. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  43771. this.cameraDirection.x = 0;
  43772. }
  43773. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  43774. this.cameraDirection.y = 0;
  43775. }
  43776. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  43777. this.cameraDirection.z = 0;
  43778. }
  43779. this.cameraDirection.scaleInPlace(this.inertia);
  43780. }
  43781. if (needToRotate) {
  43782. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  43783. this.cameraRotation.x = 0;
  43784. }
  43785. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  43786. this.cameraRotation.y = 0;
  43787. }
  43788. this.cameraRotation.scaleInPlace(this.inertia);
  43789. }
  43790. _super.prototype._checkInputs.call(this);
  43791. };
  43792. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  43793. if (this.rotationQuaternion) {
  43794. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  43795. }
  43796. else {
  43797. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  43798. }
  43799. //update the up vector!
  43800. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  43801. };
  43802. TargetCamera.prototype._getViewMatrix = function () {
  43803. if (this.lockedTarget) {
  43804. this.setTarget(this._getLockedTargetPosition());
  43805. }
  43806. // Compute
  43807. this._updateCameraRotationMatrix();
  43808. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  43809. // Computing target and final matrix
  43810. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  43811. if (this.getScene().useRightHandedSystem) {
  43812. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43813. }
  43814. else {
  43815. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this._currentUpVector, this._viewMatrix);
  43816. }
  43817. return this._viewMatrix;
  43818. };
  43819. /**
  43820. * @override
  43821. * Override Camera.createRigCamera
  43822. */
  43823. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  43824. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  43825. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  43826. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  43827. if (!this.rotationQuaternion) {
  43828. this.rotationQuaternion = new BABYLON.Quaternion();
  43829. }
  43830. rigCamera._cameraRigParams = {};
  43831. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  43832. }
  43833. return rigCamera;
  43834. }
  43835. return null;
  43836. };
  43837. /**
  43838. * @override
  43839. * Override Camera._updateRigCameras
  43840. */
  43841. TargetCamera.prototype._updateRigCameras = function () {
  43842. var camLeft = this._rigCameras[0];
  43843. var camRight = this._rigCameras[1];
  43844. switch (this.cameraRigMode) {
  43845. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  43846. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  43847. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  43848. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  43849. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  43850. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  43851. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  43852. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  43853. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  43854. camLeft.setTarget(this.getTarget());
  43855. camRight.setTarget(this.getTarget());
  43856. break;
  43857. case BABYLON.Camera.RIG_MODE_VR:
  43858. if (camLeft.rotationQuaternion) {
  43859. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43860. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  43861. }
  43862. else {
  43863. camLeft.rotation.copyFrom(this.rotation);
  43864. camRight.rotation.copyFrom(this.rotation);
  43865. }
  43866. camLeft.position.copyFrom(this.position);
  43867. camRight.position.copyFrom(this.position);
  43868. break;
  43869. }
  43870. _super.prototype._updateRigCameras.call(this);
  43871. };
  43872. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  43873. if (!this._rigCamTransformMatrix) {
  43874. this._rigCamTransformMatrix = new BABYLON.Matrix();
  43875. }
  43876. var target = this.getTarget();
  43877. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  43878. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  43879. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  43880. };
  43881. TargetCamera.prototype.getClassName = function () {
  43882. return "TargetCamera";
  43883. };
  43884. __decorate([
  43885. BABYLON.serializeAsVector3()
  43886. ], TargetCamera.prototype, "rotation", void 0);
  43887. __decorate([
  43888. BABYLON.serialize()
  43889. ], TargetCamera.prototype, "speed", void 0);
  43890. __decorate([
  43891. BABYLON.serializeAsMeshReference("lockedTargetId")
  43892. ], TargetCamera.prototype, "lockedTarget", void 0);
  43893. return TargetCamera;
  43894. }(BABYLON.Camera));
  43895. BABYLON.TargetCamera = TargetCamera;
  43896. })(BABYLON || (BABYLON = {}));
  43897. //# sourceMappingURL=babylon.targetCamera.js.map
  43898. "use strict";
  43899. var BABYLON;
  43900. (function (BABYLON) {
  43901. var FreeCameraMouseInput = /** @class */ (function () {
  43902. function FreeCameraMouseInput(touchEnabled) {
  43903. if (touchEnabled === void 0) { touchEnabled = true; }
  43904. this.touchEnabled = touchEnabled;
  43905. this.buttons = [0, 1, 2];
  43906. this.angularSensibility = 2000.0;
  43907. this.previousPosition = null;
  43908. }
  43909. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  43910. var _this = this;
  43911. var engine = this.camera.getEngine();
  43912. if (!this._pointerInput) {
  43913. this._pointerInput = function (p, s) {
  43914. var evt = p.event;
  43915. if (engine.isInVRExclusivePointerMode) {
  43916. return;
  43917. }
  43918. if (!_this.touchEnabled && evt.pointerType === "touch") {
  43919. return;
  43920. }
  43921. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  43922. return;
  43923. }
  43924. var srcElement = (evt.srcElement || evt.target);
  43925. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  43926. try {
  43927. srcElement.setPointerCapture(evt.pointerId);
  43928. }
  43929. catch (e) {
  43930. //Nothing to do with the error. Execution will continue.
  43931. }
  43932. _this.previousPosition = {
  43933. x: evt.clientX,
  43934. y: evt.clientY
  43935. };
  43936. if (!noPreventDefault) {
  43937. evt.preventDefault();
  43938. element.focus();
  43939. }
  43940. }
  43941. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  43942. try {
  43943. srcElement.releasePointerCapture(evt.pointerId);
  43944. }
  43945. catch (e) {
  43946. //Nothing to do with the error.
  43947. }
  43948. _this.previousPosition = null;
  43949. if (!noPreventDefault) {
  43950. evt.preventDefault();
  43951. }
  43952. }
  43953. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  43954. if (!_this.previousPosition || engine.isPointerLock) {
  43955. return;
  43956. }
  43957. var offsetX = evt.clientX - _this.previousPosition.x;
  43958. var offsetY = evt.clientY - _this.previousPosition.y;
  43959. if (_this.camera.getScene().useRightHandedSystem) {
  43960. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43961. }
  43962. else {
  43963. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43964. }
  43965. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43966. _this.previousPosition = {
  43967. x: evt.clientX,
  43968. y: evt.clientY
  43969. };
  43970. if (!noPreventDefault) {
  43971. evt.preventDefault();
  43972. }
  43973. }
  43974. };
  43975. }
  43976. this._onMouseMove = function (evt) {
  43977. if (!engine.isPointerLock) {
  43978. return;
  43979. }
  43980. if (engine.isInVRExclusivePointerMode) {
  43981. return;
  43982. }
  43983. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  43984. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  43985. if (_this.camera.getScene().useRightHandedSystem) {
  43986. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  43987. }
  43988. else {
  43989. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  43990. }
  43991. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  43992. _this.previousPosition = null;
  43993. if (!noPreventDefault) {
  43994. evt.preventDefault();
  43995. }
  43996. };
  43997. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  43998. element.addEventListener("mousemove", this._onMouseMove, false);
  43999. };
  44000. FreeCameraMouseInput.prototype.detachControl = function (element) {
  44001. if (this._observer && element) {
  44002. this.camera.getScene().onPointerObservable.remove(this._observer);
  44003. if (this._onMouseMove) {
  44004. element.removeEventListener("mousemove", this._onMouseMove);
  44005. }
  44006. this._observer = null;
  44007. this._onMouseMove = null;
  44008. this.previousPosition = null;
  44009. }
  44010. };
  44011. FreeCameraMouseInput.prototype.getClassName = function () {
  44012. return "FreeCameraMouseInput";
  44013. };
  44014. FreeCameraMouseInput.prototype.getSimpleName = function () {
  44015. return "mouse";
  44016. };
  44017. __decorate([
  44018. BABYLON.serialize()
  44019. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  44020. __decorate([
  44021. BABYLON.serialize()
  44022. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  44023. return FreeCameraMouseInput;
  44024. }());
  44025. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  44026. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  44027. })(BABYLON || (BABYLON = {}));
  44028. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  44029. "use strict";
  44030. var BABYLON;
  44031. (function (BABYLON) {
  44032. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  44033. function FreeCameraKeyboardMoveInput() {
  44034. this._keys = new Array();
  44035. this.keysUp = [38];
  44036. this.keysDown = [40];
  44037. this.keysLeft = [37];
  44038. this.keysRight = [39];
  44039. }
  44040. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  44041. var _this = this;
  44042. if (this._onCanvasBlurObserver) {
  44043. return;
  44044. }
  44045. this._scene = this.camera.getScene();
  44046. this._engine = this._scene.getEngine();
  44047. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  44048. _this._keys = [];
  44049. });
  44050. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  44051. var evt = info.event;
  44052. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  44053. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44054. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44055. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44056. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  44057. var index = _this._keys.indexOf(evt.keyCode);
  44058. if (index === -1) {
  44059. _this._keys.push(evt.keyCode);
  44060. }
  44061. if (!noPreventDefault) {
  44062. evt.preventDefault();
  44063. }
  44064. }
  44065. }
  44066. else {
  44067. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44068. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44069. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44070. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  44071. var index = _this._keys.indexOf(evt.keyCode);
  44072. if (index >= 0) {
  44073. _this._keys.splice(index, 1);
  44074. }
  44075. if (!noPreventDefault) {
  44076. evt.preventDefault();
  44077. }
  44078. }
  44079. }
  44080. });
  44081. };
  44082. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  44083. if (this._scene) {
  44084. if (this._onKeyboardObserver) {
  44085. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  44086. }
  44087. if (this._onCanvasBlurObserver) {
  44088. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  44089. }
  44090. this._onKeyboardObserver = null;
  44091. this._onCanvasBlurObserver = null;
  44092. }
  44093. this._keys = [];
  44094. };
  44095. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  44096. if (this._onKeyboardObserver) {
  44097. var camera = this.camera;
  44098. // Keyboard
  44099. for (var index = 0; index < this._keys.length; index++) {
  44100. var keyCode = this._keys[index];
  44101. var speed = camera._computeLocalCameraSpeed();
  44102. if (this.keysLeft.indexOf(keyCode) !== -1) {
  44103. camera._localDirection.copyFromFloats(-speed, 0, 0);
  44104. }
  44105. else if (this.keysUp.indexOf(keyCode) !== -1) {
  44106. camera._localDirection.copyFromFloats(0, 0, speed);
  44107. }
  44108. else if (this.keysRight.indexOf(keyCode) !== -1) {
  44109. camera._localDirection.copyFromFloats(speed, 0, 0);
  44110. }
  44111. else if (this.keysDown.indexOf(keyCode) !== -1) {
  44112. camera._localDirection.copyFromFloats(0, 0, -speed);
  44113. }
  44114. if (camera.getScene().useRightHandedSystem) {
  44115. camera._localDirection.z *= -1;
  44116. }
  44117. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  44118. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  44119. camera.cameraDirection.addInPlace(camera._transformedDirection);
  44120. }
  44121. }
  44122. };
  44123. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  44124. return "FreeCameraKeyboardMoveInput";
  44125. };
  44126. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  44127. this._keys = [];
  44128. };
  44129. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  44130. return "keyboard";
  44131. };
  44132. __decorate([
  44133. BABYLON.serialize()
  44134. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  44135. __decorate([
  44136. BABYLON.serialize()
  44137. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  44138. __decorate([
  44139. BABYLON.serialize()
  44140. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  44141. __decorate([
  44142. BABYLON.serialize()
  44143. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  44144. return FreeCameraKeyboardMoveInput;
  44145. }());
  44146. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  44147. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  44148. })(BABYLON || (BABYLON = {}));
  44149. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  44150. "use strict";
  44151. var BABYLON;
  44152. (function (BABYLON) {
  44153. var FreeCameraInputsManager = /** @class */ (function (_super) {
  44154. __extends(FreeCameraInputsManager, _super);
  44155. function FreeCameraInputsManager(camera) {
  44156. return _super.call(this, camera) || this;
  44157. }
  44158. FreeCameraInputsManager.prototype.addKeyboard = function () {
  44159. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  44160. return this;
  44161. };
  44162. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  44163. if (touchEnabled === void 0) { touchEnabled = true; }
  44164. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  44165. return this;
  44166. };
  44167. FreeCameraInputsManager.prototype.addGamepad = function () {
  44168. this.add(new BABYLON.FreeCameraGamepadInput());
  44169. return this;
  44170. };
  44171. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  44172. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  44173. return this;
  44174. };
  44175. FreeCameraInputsManager.prototype.addTouch = function () {
  44176. this.add(new BABYLON.FreeCameraTouchInput());
  44177. return this;
  44178. };
  44179. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  44180. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  44181. return this;
  44182. };
  44183. return FreeCameraInputsManager;
  44184. }(BABYLON.CameraInputsManager));
  44185. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  44186. })(BABYLON || (BABYLON = {}));
  44187. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  44188. "use strict";
  44189. var BABYLON;
  44190. (function (BABYLON) {
  44191. var FreeCamera = /** @class */ (function (_super) {
  44192. __extends(FreeCamera, _super);
  44193. function FreeCamera(name, position, scene) {
  44194. var _this = _super.call(this, name, position, scene) || this;
  44195. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  44196. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  44197. _this.checkCollisions = false;
  44198. _this.applyGravity = false;
  44199. _this._needMoveForGravity = false;
  44200. _this._oldPosition = BABYLON.Vector3.Zero();
  44201. _this._diffPosition = BABYLON.Vector3.Zero();
  44202. _this._newPosition = BABYLON.Vector3.Zero();
  44203. // Collisions
  44204. _this._collisionMask = -1;
  44205. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  44206. if (collidedMesh === void 0) { collidedMesh = null; }
  44207. //TODO move this to the collision coordinator!
  44208. if (_this.getScene().workerCollisions)
  44209. newPosition.multiplyInPlace(_this._collider._radius);
  44210. var updatePosition = function (newPos) {
  44211. _this._newPosition.copyFrom(newPos);
  44212. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  44213. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  44214. _this.position.addInPlace(_this._diffPosition);
  44215. if (_this.onCollide && collidedMesh) {
  44216. _this.onCollide(collidedMesh);
  44217. }
  44218. }
  44219. };
  44220. updatePosition(newPosition);
  44221. };
  44222. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  44223. _this.inputs.addKeyboard().addMouse();
  44224. return _this;
  44225. }
  44226. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  44227. //-- begin properties for backward compatibility for inputs
  44228. /**
  44229. * Gets the input sensibility for a mouse input. (default is 2000.0)
  44230. * Higher values reduce sensitivity.
  44231. */
  44232. get: function () {
  44233. var mouse = this.inputs.attached["mouse"];
  44234. if (mouse)
  44235. return mouse.angularSensibility;
  44236. return 0;
  44237. },
  44238. /**
  44239. * Sets the input sensibility for a mouse input. (default is 2000.0)
  44240. * Higher values reduce sensitivity.
  44241. */
  44242. set: function (value) {
  44243. var mouse = this.inputs.attached["mouse"];
  44244. if (mouse)
  44245. mouse.angularSensibility = value;
  44246. },
  44247. enumerable: true,
  44248. configurable: true
  44249. });
  44250. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  44251. get: function () {
  44252. var keyboard = this.inputs.attached["keyboard"];
  44253. if (keyboard)
  44254. return keyboard.keysUp;
  44255. return [];
  44256. },
  44257. set: function (value) {
  44258. var keyboard = this.inputs.attached["keyboard"];
  44259. if (keyboard)
  44260. keyboard.keysUp = value;
  44261. },
  44262. enumerable: true,
  44263. configurable: true
  44264. });
  44265. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  44266. get: function () {
  44267. var keyboard = this.inputs.attached["keyboard"];
  44268. if (keyboard)
  44269. return keyboard.keysDown;
  44270. return [];
  44271. },
  44272. set: function (value) {
  44273. var keyboard = this.inputs.attached["keyboard"];
  44274. if (keyboard)
  44275. keyboard.keysDown = value;
  44276. },
  44277. enumerable: true,
  44278. configurable: true
  44279. });
  44280. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  44281. get: function () {
  44282. var keyboard = this.inputs.attached["keyboard"];
  44283. if (keyboard)
  44284. return keyboard.keysLeft;
  44285. return [];
  44286. },
  44287. set: function (value) {
  44288. var keyboard = this.inputs.attached["keyboard"];
  44289. if (keyboard)
  44290. keyboard.keysLeft = value;
  44291. },
  44292. enumerable: true,
  44293. configurable: true
  44294. });
  44295. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  44296. get: function () {
  44297. var keyboard = this.inputs.attached["keyboard"];
  44298. if (keyboard)
  44299. return keyboard.keysRight;
  44300. return [];
  44301. },
  44302. set: function (value) {
  44303. var keyboard = this.inputs.attached["keyboard"];
  44304. if (keyboard)
  44305. keyboard.keysRight = value;
  44306. },
  44307. enumerable: true,
  44308. configurable: true
  44309. });
  44310. // Controls
  44311. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  44312. this.inputs.attachElement(element, noPreventDefault);
  44313. };
  44314. FreeCamera.prototype.detachControl = function (element) {
  44315. this.inputs.detachElement(element);
  44316. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  44317. this.cameraRotation = new BABYLON.Vector2(0, 0);
  44318. };
  44319. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  44320. get: function () {
  44321. return this._collisionMask;
  44322. },
  44323. set: function (mask) {
  44324. this._collisionMask = !isNaN(mask) ? mask : -1;
  44325. },
  44326. enumerable: true,
  44327. configurable: true
  44328. });
  44329. FreeCamera.prototype._collideWithWorld = function (displacement) {
  44330. var globalPosition;
  44331. if (this.parent) {
  44332. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  44333. }
  44334. else {
  44335. globalPosition = this.position;
  44336. }
  44337. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  44338. this._oldPosition.addInPlace(this.ellipsoidOffset);
  44339. if (!this._collider) {
  44340. this._collider = new BABYLON.Collider();
  44341. }
  44342. this._collider._radius = this.ellipsoid;
  44343. this._collider.collisionMask = this._collisionMask;
  44344. //no need for clone, as long as gravity is not on.
  44345. var actualDisplacement = displacement;
  44346. //add gravity to the direction to prevent the dual-collision checking
  44347. if (this.applyGravity) {
  44348. //this prevents mending with cameraDirection, a global variable of the free camera class.
  44349. actualDisplacement = displacement.add(this.getScene().gravity);
  44350. }
  44351. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  44352. };
  44353. FreeCamera.prototype._checkInputs = function () {
  44354. if (!this._localDirection) {
  44355. this._localDirection = BABYLON.Vector3.Zero();
  44356. this._transformedDirection = BABYLON.Vector3.Zero();
  44357. }
  44358. this.inputs.checkInputs();
  44359. _super.prototype._checkInputs.call(this);
  44360. };
  44361. FreeCamera.prototype._decideIfNeedsToMove = function () {
  44362. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  44363. };
  44364. FreeCamera.prototype._updatePosition = function () {
  44365. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  44366. this._collideWithWorld(this.cameraDirection);
  44367. }
  44368. else {
  44369. _super.prototype._updatePosition.call(this);
  44370. }
  44371. };
  44372. FreeCamera.prototype.dispose = function () {
  44373. this.inputs.clear();
  44374. _super.prototype.dispose.call(this);
  44375. };
  44376. FreeCamera.prototype.getClassName = function () {
  44377. return "FreeCamera";
  44378. };
  44379. __decorate([
  44380. BABYLON.serializeAsVector3()
  44381. ], FreeCamera.prototype, "ellipsoid", void 0);
  44382. __decorate([
  44383. BABYLON.serializeAsVector3()
  44384. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  44385. __decorate([
  44386. BABYLON.serialize()
  44387. ], FreeCamera.prototype, "checkCollisions", void 0);
  44388. __decorate([
  44389. BABYLON.serialize()
  44390. ], FreeCamera.prototype, "applyGravity", void 0);
  44391. return FreeCamera;
  44392. }(BABYLON.TargetCamera));
  44393. BABYLON.FreeCamera = FreeCamera;
  44394. })(BABYLON || (BABYLON = {}));
  44395. //# sourceMappingURL=babylon.freeCamera.js.map
  44396. "use strict";
  44397. var BABYLON;
  44398. (function (BABYLON) {
  44399. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  44400. function ArcRotateCameraKeyboardMoveInput() {
  44401. this._keys = new Array();
  44402. this.keysUp = [38];
  44403. this.keysDown = [40];
  44404. this.keysLeft = [37];
  44405. this.keysRight = [39];
  44406. this.keysReset = [220];
  44407. this.panningSensibility = 50.0;
  44408. this.zoomingSensibility = 25.0;
  44409. this.useAltToZoom = true;
  44410. }
  44411. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  44412. var _this = this;
  44413. if (this._onCanvasBlurObserver) {
  44414. return;
  44415. }
  44416. this._scene = this.camera.getScene();
  44417. this._engine = this._scene.getEngine();
  44418. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  44419. _this._keys = [];
  44420. });
  44421. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  44422. var evt = info.event;
  44423. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  44424. _this._ctrlPressed = evt.ctrlKey;
  44425. _this._altPressed = evt.altKey;
  44426. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44427. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44428. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44429. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  44430. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  44431. var index = _this._keys.indexOf(evt.keyCode);
  44432. if (index === -1) {
  44433. _this._keys.push(evt.keyCode);
  44434. }
  44435. if (evt.preventDefault) {
  44436. if (!noPreventDefault) {
  44437. evt.preventDefault();
  44438. }
  44439. }
  44440. }
  44441. }
  44442. else {
  44443. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  44444. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  44445. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  44446. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  44447. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  44448. var index = _this._keys.indexOf(evt.keyCode);
  44449. if (index >= 0) {
  44450. _this._keys.splice(index, 1);
  44451. }
  44452. if (evt.preventDefault) {
  44453. if (!noPreventDefault) {
  44454. evt.preventDefault();
  44455. }
  44456. }
  44457. }
  44458. }
  44459. });
  44460. };
  44461. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  44462. if (this._scene) {
  44463. if (this._onKeyboardObserver) {
  44464. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  44465. }
  44466. if (this._onCanvasBlurObserver) {
  44467. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  44468. }
  44469. this._onKeyboardObserver = null;
  44470. this._onCanvasBlurObserver = null;
  44471. }
  44472. this._keys = [];
  44473. };
  44474. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  44475. if (this._onKeyboardObserver) {
  44476. var camera = this.camera;
  44477. for (var index = 0; index < this._keys.length; index++) {
  44478. var keyCode = this._keys[index];
  44479. if (this.keysLeft.indexOf(keyCode) !== -1) {
  44480. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44481. camera.inertialPanningX -= 1 / this.panningSensibility;
  44482. }
  44483. else {
  44484. camera.inertialAlphaOffset -= 0.01;
  44485. }
  44486. }
  44487. else if (this.keysUp.indexOf(keyCode) !== -1) {
  44488. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44489. camera.inertialPanningY += 1 / this.panningSensibility;
  44490. }
  44491. else if (this._altPressed && this.useAltToZoom) {
  44492. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  44493. }
  44494. else {
  44495. camera.inertialBetaOffset -= 0.01;
  44496. }
  44497. }
  44498. else if (this.keysRight.indexOf(keyCode) !== -1) {
  44499. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44500. camera.inertialPanningX += 1 / this.panningSensibility;
  44501. }
  44502. else {
  44503. camera.inertialAlphaOffset += 0.01;
  44504. }
  44505. }
  44506. else if (this.keysDown.indexOf(keyCode) !== -1) {
  44507. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  44508. camera.inertialPanningY -= 1 / this.panningSensibility;
  44509. }
  44510. else if (this._altPressed && this.useAltToZoom) {
  44511. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  44512. }
  44513. else {
  44514. camera.inertialBetaOffset += 0.01;
  44515. }
  44516. }
  44517. else if (this.keysReset.indexOf(keyCode) !== -1) {
  44518. camera.restoreState();
  44519. }
  44520. }
  44521. }
  44522. };
  44523. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  44524. return "ArcRotateCameraKeyboardMoveInput";
  44525. };
  44526. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  44527. return "keyboard";
  44528. };
  44529. __decorate([
  44530. BABYLON.serialize()
  44531. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  44532. __decorate([
  44533. BABYLON.serialize()
  44534. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  44535. __decorate([
  44536. BABYLON.serialize()
  44537. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  44538. __decorate([
  44539. BABYLON.serialize()
  44540. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  44541. __decorate([
  44542. BABYLON.serialize()
  44543. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  44544. __decorate([
  44545. BABYLON.serialize()
  44546. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  44547. __decorate([
  44548. BABYLON.serialize()
  44549. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  44550. __decorate([
  44551. BABYLON.serialize()
  44552. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  44553. return ArcRotateCameraKeyboardMoveInput;
  44554. }());
  44555. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  44556. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  44557. })(BABYLON || (BABYLON = {}));
  44558. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  44559. "use strict";
  44560. var BABYLON;
  44561. (function (BABYLON) {
  44562. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  44563. function ArcRotateCameraMouseWheelInput() {
  44564. this.wheelPrecision = 3.0;
  44565. /**
  44566. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  44567. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  44568. */
  44569. this.wheelDeltaPercentage = 0;
  44570. }
  44571. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  44572. var _this = this;
  44573. this._wheel = function (p, s) {
  44574. //sanity check - this should be a PointerWheel event.
  44575. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  44576. return;
  44577. var event = p.event;
  44578. var delta = 0;
  44579. if (event.wheelDelta) {
  44580. delta = _this.wheelDeltaPercentage ? (event.wheelDelta * 0.01) * _this.camera.radius * _this.wheelDeltaPercentage : event.wheelDelta / (_this.wheelPrecision * 40);
  44581. }
  44582. else if (event.detail) {
  44583. delta = -event.detail / _this.wheelPrecision;
  44584. }
  44585. if (delta)
  44586. _this.camera.inertialRadiusOffset += delta;
  44587. if (event.preventDefault) {
  44588. if (!noPreventDefault) {
  44589. event.preventDefault();
  44590. }
  44591. }
  44592. };
  44593. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  44594. };
  44595. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  44596. if (this._observer && element) {
  44597. this.camera.getScene().onPointerObservable.remove(this._observer);
  44598. this._observer = null;
  44599. this._wheel = null;
  44600. }
  44601. };
  44602. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  44603. return "ArcRotateCameraMouseWheelInput";
  44604. };
  44605. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  44606. return "mousewheel";
  44607. };
  44608. __decorate([
  44609. BABYLON.serialize()
  44610. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  44611. __decorate([
  44612. BABYLON.serialize()
  44613. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  44614. return ArcRotateCameraMouseWheelInput;
  44615. }());
  44616. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  44617. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  44618. })(BABYLON || (BABYLON = {}));
  44619. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  44620. "use strict";
  44621. var BABYLON;
  44622. (function (BABYLON) {
  44623. var ArcRotateCameraPointersInput = /** @class */ (function () {
  44624. function ArcRotateCameraPointersInput() {
  44625. this.buttons = [0, 1, 2];
  44626. this.angularSensibilityX = 1000.0;
  44627. this.angularSensibilityY = 1000.0;
  44628. this.pinchPrecision = 12.0;
  44629. /**
  44630. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  44631. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  44632. */
  44633. this.pinchDeltaPercentage = 0;
  44634. this.panningSensibility = 1000.0;
  44635. this.multiTouchPanning = true;
  44636. this.multiTouchPanAndZoom = true;
  44637. this._isPanClick = false;
  44638. this.pinchInwards = true;
  44639. }
  44640. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  44641. var _this = this;
  44642. var engine = this.camera.getEngine();
  44643. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  44644. var pointA = null;
  44645. var pointB = null;
  44646. var previousPinchSquaredDistance = 0;
  44647. var initialDistance = 0;
  44648. var twoFingerActivityCount = 0;
  44649. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  44650. this._pointerInput = function (p, s) {
  44651. var evt = p.event;
  44652. var isTouch = p.event.pointerType === "touch";
  44653. if (engine.isInVRExclusivePointerMode) {
  44654. return;
  44655. }
  44656. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  44657. return;
  44658. }
  44659. var srcElement = (evt.srcElement || evt.target);
  44660. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  44661. try {
  44662. srcElement.setPointerCapture(evt.pointerId);
  44663. }
  44664. catch (e) {
  44665. //Nothing to do with the error. Execution will continue.
  44666. }
  44667. // Manage panning with pan button click
  44668. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  44669. // manage pointers
  44670. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  44671. if (pointA === null) {
  44672. pointA = cacheSoloPointer;
  44673. }
  44674. else if (pointB === null) {
  44675. pointB = cacheSoloPointer;
  44676. }
  44677. if (!noPreventDefault) {
  44678. evt.preventDefault();
  44679. element.focus();
  44680. }
  44681. }
  44682. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  44683. _this.camera.restoreState();
  44684. }
  44685. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  44686. try {
  44687. srcElement.releasePointerCapture(evt.pointerId);
  44688. }
  44689. catch (e) {
  44690. //Nothing to do with the error.
  44691. }
  44692. cacheSoloPointer = null;
  44693. previousPinchSquaredDistance = 0;
  44694. previousMultiTouchPanPosition.isPaning = false;
  44695. previousMultiTouchPanPosition.isPinching = false;
  44696. twoFingerActivityCount = 0;
  44697. initialDistance = 0;
  44698. if (!isTouch) {
  44699. pointB = null; // Mouse and pen are mono pointer
  44700. }
  44701. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  44702. //but emptying completly pointers collection is required to fix a bug on iPhone :
  44703. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  44704. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  44705. if (engine.badOS) {
  44706. pointA = pointB = null;
  44707. }
  44708. else {
  44709. //only remove the impacted pointer in case of multitouch allowing on most
  44710. //platforms switching from rotate to zoom and pan seamlessly.
  44711. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  44712. pointA = pointB;
  44713. pointB = null;
  44714. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44715. }
  44716. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  44717. pointB = null;
  44718. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  44719. }
  44720. else {
  44721. pointA = pointB = null;
  44722. }
  44723. }
  44724. if (!noPreventDefault) {
  44725. evt.preventDefault();
  44726. }
  44727. }
  44728. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  44729. if (!noPreventDefault) {
  44730. evt.preventDefault();
  44731. }
  44732. // One button down
  44733. if (pointA && pointB === null && cacheSoloPointer) {
  44734. if (_this.panningSensibility !== 0 &&
  44735. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  44736. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  44737. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  44738. }
  44739. else {
  44740. var offsetX = evt.clientX - cacheSoloPointer.x;
  44741. var offsetY = evt.clientY - cacheSoloPointer.y;
  44742. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44743. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44744. }
  44745. cacheSoloPointer.x = evt.clientX;
  44746. cacheSoloPointer.y = evt.clientY;
  44747. }
  44748. else if (pointA && pointB) {
  44749. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  44750. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  44751. ed.x = evt.clientX;
  44752. ed.y = evt.clientY;
  44753. var direction = _this.pinchInwards ? 1 : -1;
  44754. var distX = pointA.x - pointB.x;
  44755. var distY = pointA.y - pointB.y;
  44756. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  44757. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  44758. if (previousPinchSquaredDistance === 0) {
  44759. initialDistance = pinchDistance;
  44760. previousPinchSquaredDistance = pinchSquaredDistance;
  44761. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  44762. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  44763. return;
  44764. }
  44765. if (_this.multiTouchPanAndZoom) {
  44766. if (_this.pinchDeltaPercentage) {
  44767. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44768. }
  44769. else {
  44770. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44771. (_this.pinchPrecision *
  44772. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44773. direction);
  44774. }
  44775. if (_this.panningSensibility !== 0) {
  44776. var pointersCenterX = (pointA.x + pointB.x) / 2;
  44777. var pointersCenterY = (pointA.y + pointB.y) / 2;
  44778. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  44779. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  44780. previousMultiTouchPanPosition.x = pointersCenterX;
  44781. previousMultiTouchPanPosition.y = pointersCenterY;
  44782. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  44783. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  44784. }
  44785. }
  44786. else {
  44787. twoFingerActivityCount++;
  44788. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  44789. if (_this.pinchDeltaPercentage) {
  44790. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  44791. }
  44792. else {
  44793. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  44794. (_this.pinchPrecision *
  44795. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  44796. direction);
  44797. }
  44798. previousMultiTouchPanPosition.isPaning = false;
  44799. previousMultiTouchPanPosition.isPinching = true;
  44800. }
  44801. else {
  44802. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  44803. if (!previousMultiTouchPanPosition.isPaning) {
  44804. previousMultiTouchPanPosition.isPaning = true;
  44805. previousMultiTouchPanPosition.isPinching = false;
  44806. previousMultiTouchPanPosition.x = ed.x;
  44807. previousMultiTouchPanPosition.y = ed.y;
  44808. return;
  44809. }
  44810. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  44811. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  44812. }
  44813. }
  44814. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  44815. previousMultiTouchPanPosition.x = ed.x;
  44816. previousMultiTouchPanPosition.y = ed.y;
  44817. }
  44818. }
  44819. previousPinchSquaredDistance = pinchSquaredDistance;
  44820. }
  44821. }
  44822. };
  44823. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  44824. this._onContextMenu = function (evt) {
  44825. evt.preventDefault();
  44826. };
  44827. if (!this.camera._useCtrlForPanning) {
  44828. element.addEventListener("contextmenu", this._onContextMenu, false);
  44829. }
  44830. this._onLostFocus = function () {
  44831. //this._keys = [];
  44832. pointA = pointB = null;
  44833. previousPinchSquaredDistance = 0;
  44834. previousMultiTouchPanPosition.isPaning = false;
  44835. previousMultiTouchPanPosition.isPinching = false;
  44836. twoFingerActivityCount = 0;
  44837. cacheSoloPointer = null;
  44838. initialDistance = 0;
  44839. };
  44840. this._onMouseMove = function (evt) {
  44841. if (!engine.isPointerLock) {
  44842. return;
  44843. }
  44844. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  44845. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  44846. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  44847. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  44848. if (!noPreventDefault) {
  44849. evt.preventDefault();
  44850. }
  44851. };
  44852. this._onGestureStart = function (e) {
  44853. if (window.MSGesture === undefined) {
  44854. return;
  44855. }
  44856. if (!_this._MSGestureHandler) {
  44857. _this._MSGestureHandler = new MSGesture();
  44858. _this._MSGestureHandler.target = element;
  44859. }
  44860. _this._MSGestureHandler.addPointer(e.pointerId);
  44861. };
  44862. this._onGesture = function (e) {
  44863. _this.camera.radius *= e.scale;
  44864. if (e.preventDefault) {
  44865. if (!noPreventDefault) {
  44866. e.stopPropagation();
  44867. e.preventDefault();
  44868. }
  44869. }
  44870. };
  44871. element.addEventListener("mousemove", this._onMouseMove, false);
  44872. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  44873. element.addEventListener("MSGestureChange", this._onGesture, false);
  44874. BABYLON.Tools.RegisterTopRootEvents([
  44875. { name: "blur", handler: this._onLostFocus }
  44876. ]);
  44877. };
  44878. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  44879. if (this._onLostFocus) {
  44880. BABYLON.Tools.UnregisterTopRootEvents([
  44881. { name: "blur", handler: this._onLostFocus }
  44882. ]);
  44883. }
  44884. if (element && this._observer) {
  44885. this.camera.getScene().onPointerObservable.remove(this._observer);
  44886. this._observer = null;
  44887. if (this._onContextMenu) {
  44888. element.removeEventListener("contextmenu", this._onContextMenu);
  44889. }
  44890. if (this._onMouseMove) {
  44891. element.removeEventListener("mousemove", this._onMouseMove);
  44892. }
  44893. if (this._onGestureStart) {
  44894. element.removeEventListener("MSPointerDown", this._onGestureStart);
  44895. }
  44896. if (this._onGesture) {
  44897. element.removeEventListener("MSGestureChange", this._onGesture);
  44898. }
  44899. this._isPanClick = false;
  44900. this.pinchInwards = true;
  44901. this._onMouseMove = null;
  44902. this._onGestureStart = null;
  44903. this._onGesture = null;
  44904. this._MSGestureHandler = null;
  44905. this._onLostFocus = null;
  44906. this._onContextMenu = null;
  44907. }
  44908. };
  44909. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  44910. return "ArcRotateCameraPointersInput";
  44911. };
  44912. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  44913. return "pointers";
  44914. };
  44915. __decorate([
  44916. BABYLON.serialize()
  44917. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  44918. __decorate([
  44919. BABYLON.serialize()
  44920. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  44921. __decorate([
  44922. BABYLON.serialize()
  44923. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  44924. __decorate([
  44925. BABYLON.serialize()
  44926. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  44927. __decorate([
  44928. BABYLON.serialize()
  44929. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  44930. __decorate([
  44931. BABYLON.serialize()
  44932. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  44933. __decorate([
  44934. BABYLON.serialize()
  44935. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  44936. __decorate([
  44937. BABYLON.serialize()
  44938. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  44939. return ArcRotateCameraPointersInput;
  44940. }());
  44941. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  44942. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  44943. })(BABYLON || (BABYLON = {}));
  44944. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  44945. "use strict";
  44946. var BABYLON;
  44947. (function (BABYLON) {
  44948. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  44949. __extends(ArcRotateCameraInputsManager, _super);
  44950. function ArcRotateCameraInputsManager(camera) {
  44951. return _super.call(this, camera) || this;
  44952. }
  44953. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  44954. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  44955. return this;
  44956. };
  44957. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  44958. this.add(new BABYLON.ArcRotateCameraPointersInput());
  44959. return this;
  44960. };
  44961. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  44962. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  44963. return this;
  44964. };
  44965. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  44966. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  44967. return this;
  44968. };
  44969. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  44970. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  44971. return this;
  44972. };
  44973. return ArcRotateCameraInputsManager;
  44974. }(BABYLON.CameraInputsManager));
  44975. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  44976. })(BABYLON || (BABYLON = {}));
  44977. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  44978. "use strict";
  44979. var BABYLON;
  44980. (function (BABYLON) {
  44981. var ArcRotateCamera = /** @class */ (function (_super) {
  44982. __extends(ArcRotateCamera, _super);
  44983. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  44984. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  44985. _this.inertialAlphaOffset = 0;
  44986. _this.inertialBetaOffset = 0;
  44987. _this.inertialRadiusOffset = 0;
  44988. _this.lowerAlphaLimit = null;
  44989. _this.upperAlphaLimit = null;
  44990. _this.lowerBetaLimit = 0.01;
  44991. _this.upperBetaLimit = Math.PI;
  44992. _this.lowerRadiusLimit = null;
  44993. _this.upperRadiusLimit = null;
  44994. _this.inertialPanningX = 0;
  44995. _this.inertialPanningY = 0;
  44996. _this.pinchToPanMaxDistance = 20;
  44997. _this.panningDistanceLimit = null;
  44998. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  44999. _this.panningInertia = 0.9;
  45000. //-- end properties for backward compatibility for inputs
  45001. _this.zoomOnFactor = 1;
  45002. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  45003. _this.allowUpsideDown = true;
  45004. _this._viewMatrix = new BABYLON.Matrix();
  45005. // Panning
  45006. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  45007. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  45008. _this.checkCollisions = false;
  45009. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  45010. _this._previousPosition = BABYLON.Vector3.Zero();
  45011. _this._collisionVelocity = BABYLON.Vector3.Zero();
  45012. _this._newPosition = BABYLON.Vector3.Zero();
  45013. _this._computationVector = BABYLON.Vector3.Zero();
  45014. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  45015. if (collidedMesh === void 0) { collidedMesh = null; }
  45016. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  45017. newPosition.multiplyInPlace(_this._collider._radius);
  45018. }
  45019. if (!collidedMesh) {
  45020. _this._previousPosition.copyFrom(_this.position);
  45021. }
  45022. else {
  45023. _this.setPosition(newPosition);
  45024. if (_this.onCollide) {
  45025. _this.onCollide(collidedMesh);
  45026. }
  45027. }
  45028. // Recompute because of constraints
  45029. var cosa = Math.cos(_this.alpha);
  45030. var sina = Math.sin(_this.alpha);
  45031. var cosb = Math.cos(_this.beta);
  45032. var sinb = Math.sin(_this.beta);
  45033. if (sinb === 0) {
  45034. sinb = 0.0001;
  45035. }
  45036. var target = _this._getTargetPosition();
  45037. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  45038. target.addToRef(_this._computationVector, _this._newPosition);
  45039. _this.position.copyFrom(_this._newPosition);
  45040. var up = _this.upVector;
  45041. if (_this.allowUpsideDown && _this.beta < 0) {
  45042. up = up.clone();
  45043. up = up.negate();
  45044. }
  45045. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  45046. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  45047. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  45048. _this._collisionTriggered = false;
  45049. };
  45050. _this._target = BABYLON.Vector3.Zero();
  45051. if (target) {
  45052. _this.setTarget(target);
  45053. }
  45054. _this.alpha = alpha;
  45055. _this.beta = beta;
  45056. _this.radius = radius;
  45057. _this.getViewMatrix();
  45058. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  45059. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  45060. return _this;
  45061. }
  45062. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  45063. get: function () {
  45064. return this._target;
  45065. },
  45066. set: function (value) {
  45067. this.setTarget(value);
  45068. },
  45069. enumerable: true,
  45070. configurable: true
  45071. });
  45072. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  45073. //-- begin properties for backward compatibility for inputs
  45074. get: function () {
  45075. var pointers = this.inputs.attached["pointers"];
  45076. if (pointers)
  45077. return pointers.angularSensibilityX;
  45078. return 0;
  45079. },
  45080. set: function (value) {
  45081. var pointers = this.inputs.attached["pointers"];
  45082. if (pointers) {
  45083. pointers.angularSensibilityX = value;
  45084. }
  45085. },
  45086. enumerable: true,
  45087. configurable: true
  45088. });
  45089. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  45090. get: function () {
  45091. var pointers = this.inputs.attached["pointers"];
  45092. if (pointers)
  45093. return pointers.angularSensibilityY;
  45094. return 0;
  45095. },
  45096. set: function (value) {
  45097. var pointers = this.inputs.attached["pointers"];
  45098. if (pointers) {
  45099. pointers.angularSensibilityY = value;
  45100. }
  45101. },
  45102. enumerable: true,
  45103. configurable: true
  45104. });
  45105. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  45106. get: function () {
  45107. var pointers = this.inputs.attached["pointers"];
  45108. if (pointers)
  45109. return pointers.pinchPrecision;
  45110. return 0;
  45111. },
  45112. set: function (value) {
  45113. var pointers = this.inputs.attached["pointers"];
  45114. if (pointers) {
  45115. pointers.pinchPrecision = value;
  45116. }
  45117. },
  45118. enumerable: true,
  45119. configurable: true
  45120. });
  45121. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  45122. get: function () {
  45123. var pointers = this.inputs.attached["pointers"];
  45124. if (pointers)
  45125. return pointers.pinchDeltaPercentage;
  45126. return 0;
  45127. },
  45128. set: function (value) {
  45129. var pointers = this.inputs.attached["pointers"];
  45130. if (pointers) {
  45131. pointers.pinchDeltaPercentage = value;
  45132. }
  45133. },
  45134. enumerable: true,
  45135. configurable: true
  45136. });
  45137. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  45138. get: function () {
  45139. var pointers = this.inputs.attached["pointers"];
  45140. if (pointers)
  45141. return pointers.panningSensibility;
  45142. return 0;
  45143. },
  45144. set: function (value) {
  45145. var pointers = this.inputs.attached["pointers"];
  45146. if (pointers) {
  45147. pointers.panningSensibility = value;
  45148. }
  45149. },
  45150. enumerable: true,
  45151. configurable: true
  45152. });
  45153. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  45154. get: function () {
  45155. var keyboard = this.inputs.attached["keyboard"];
  45156. if (keyboard)
  45157. return keyboard.keysUp;
  45158. return [];
  45159. },
  45160. set: function (value) {
  45161. var keyboard = this.inputs.attached["keyboard"];
  45162. if (keyboard)
  45163. keyboard.keysUp = value;
  45164. },
  45165. enumerable: true,
  45166. configurable: true
  45167. });
  45168. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  45169. get: function () {
  45170. var keyboard = this.inputs.attached["keyboard"];
  45171. if (keyboard)
  45172. return keyboard.keysDown;
  45173. return [];
  45174. },
  45175. set: function (value) {
  45176. var keyboard = this.inputs.attached["keyboard"];
  45177. if (keyboard)
  45178. keyboard.keysDown = value;
  45179. },
  45180. enumerable: true,
  45181. configurable: true
  45182. });
  45183. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  45184. get: function () {
  45185. var keyboard = this.inputs.attached["keyboard"];
  45186. if (keyboard)
  45187. return keyboard.keysLeft;
  45188. return [];
  45189. },
  45190. set: function (value) {
  45191. var keyboard = this.inputs.attached["keyboard"];
  45192. if (keyboard)
  45193. keyboard.keysLeft = value;
  45194. },
  45195. enumerable: true,
  45196. configurable: true
  45197. });
  45198. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  45199. get: function () {
  45200. var keyboard = this.inputs.attached["keyboard"];
  45201. if (keyboard)
  45202. return keyboard.keysRight;
  45203. return [];
  45204. },
  45205. set: function (value) {
  45206. var keyboard = this.inputs.attached["keyboard"];
  45207. if (keyboard)
  45208. keyboard.keysRight = value;
  45209. },
  45210. enumerable: true,
  45211. configurable: true
  45212. });
  45213. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  45214. get: function () {
  45215. var mousewheel = this.inputs.attached["mousewheel"];
  45216. if (mousewheel)
  45217. return mousewheel.wheelPrecision;
  45218. return 0;
  45219. },
  45220. set: function (value) {
  45221. var mousewheel = this.inputs.attached["mousewheel"];
  45222. if (mousewheel)
  45223. mousewheel.wheelPrecision = value;
  45224. },
  45225. enumerable: true,
  45226. configurable: true
  45227. });
  45228. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  45229. get: function () {
  45230. var mousewheel = this.inputs.attached["mousewheel"];
  45231. if (mousewheel)
  45232. return mousewheel.wheelDeltaPercentage;
  45233. return 0;
  45234. },
  45235. set: function (value) {
  45236. var mousewheel = this.inputs.attached["mousewheel"];
  45237. if (mousewheel)
  45238. mousewheel.wheelDeltaPercentage = value;
  45239. },
  45240. enumerable: true,
  45241. configurable: true
  45242. });
  45243. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  45244. get: function () {
  45245. return this._bouncingBehavior;
  45246. },
  45247. enumerable: true,
  45248. configurable: true
  45249. });
  45250. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  45251. get: function () {
  45252. return this._bouncingBehavior != null;
  45253. },
  45254. set: function (value) {
  45255. if (value === this.useBouncingBehavior) {
  45256. return;
  45257. }
  45258. if (value) {
  45259. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  45260. this.addBehavior(this._bouncingBehavior);
  45261. }
  45262. else if (this._bouncingBehavior) {
  45263. this.removeBehavior(this._bouncingBehavior);
  45264. this._bouncingBehavior = null;
  45265. }
  45266. },
  45267. enumerable: true,
  45268. configurable: true
  45269. });
  45270. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  45271. get: function () {
  45272. return this._framingBehavior;
  45273. },
  45274. enumerable: true,
  45275. configurable: true
  45276. });
  45277. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  45278. get: function () {
  45279. return this._framingBehavior != null;
  45280. },
  45281. set: function (value) {
  45282. if (value === this.useFramingBehavior) {
  45283. return;
  45284. }
  45285. if (value) {
  45286. this._framingBehavior = new BABYLON.FramingBehavior();
  45287. this.addBehavior(this._framingBehavior);
  45288. }
  45289. else if (this._framingBehavior) {
  45290. this.removeBehavior(this._framingBehavior);
  45291. this._framingBehavior = null;
  45292. }
  45293. },
  45294. enumerable: true,
  45295. configurable: true
  45296. });
  45297. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  45298. get: function () {
  45299. return this._autoRotationBehavior;
  45300. },
  45301. enumerable: true,
  45302. configurable: true
  45303. });
  45304. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  45305. get: function () {
  45306. return this._autoRotationBehavior != null;
  45307. },
  45308. set: function (value) {
  45309. if (value === this.useAutoRotationBehavior) {
  45310. return;
  45311. }
  45312. if (value) {
  45313. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  45314. this.addBehavior(this._autoRotationBehavior);
  45315. }
  45316. else if (this._autoRotationBehavior) {
  45317. this.removeBehavior(this._autoRotationBehavior);
  45318. this._autoRotationBehavior = null;
  45319. }
  45320. },
  45321. enumerable: true,
  45322. configurable: true
  45323. });
  45324. // Cache
  45325. ArcRotateCamera.prototype._initCache = function () {
  45326. _super.prototype._initCache.call(this);
  45327. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  45328. this._cache.alpha = undefined;
  45329. this._cache.beta = undefined;
  45330. this._cache.radius = undefined;
  45331. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  45332. };
  45333. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  45334. if (!ignoreParentClass) {
  45335. _super.prototype._updateCache.call(this);
  45336. }
  45337. this._cache._target.copyFrom(this._getTargetPosition());
  45338. this._cache.alpha = this.alpha;
  45339. this._cache.beta = this.beta;
  45340. this._cache.radius = this.radius;
  45341. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  45342. };
  45343. ArcRotateCamera.prototype._getTargetPosition = function () {
  45344. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  45345. var pos = this._targetHost.getAbsolutePosition();
  45346. if (this._targetBoundingCenter) {
  45347. pos.addToRef(this._targetBoundingCenter, this._target);
  45348. }
  45349. else {
  45350. this._target.copyFrom(pos);
  45351. }
  45352. }
  45353. var lockedTargetPosition = this._getLockedTargetPosition();
  45354. if (lockedTargetPosition) {
  45355. return lockedTargetPosition;
  45356. }
  45357. return this._target;
  45358. };
  45359. ArcRotateCamera.prototype.storeState = function () {
  45360. this._storedAlpha = this.alpha;
  45361. this._storedBeta = this.beta;
  45362. this._storedRadius = this.radius;
  45363. this._storedTarget = this._getTargetPosition().clone();
  45364. return _super.prototype.storeState.call(this);
  45365. };
  45366. /**
  45367. * Restored camera state. You must call storeState() first
  45368. */
  45369. ArcRotateCamera.prototype._restoreStateValues = function () {
  45370. if (!_super.prototype._restoreStateValues.call(this)) {
  45371. return false;
  45372. }
  45373. this.alpha = this._storedAlpha;
  45374. this.beta = this._storedBeta;
  45375. this.radius = this._storedRadius;
  45376. this.setTarget(this._storedTarget.clone());
  45377. this.inertialAlphaOffset = 0;
  45378. this.inertialBetaOffset = 0;
  45379. this.inertialRadiusOffset = 0;
  45380. this.inertialPanningX = 0;
  45381. this.inertialPanningY = 0;
  45382. return true;
  45383. };
  45384. // Synchronized
  45385. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  45386. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  45387. return false;
  45388. return this._cache._target.equals(this._getTargetPosition())
  45389. && this._cache.alpha === this.alpha
  45390. && this._cache.beta === this.beta
  45391. && this._cache.radius === this.radius
  45392. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  45393. };
  45394. // Methods
  45395. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  45396. var _this = this;
  45397. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  45398. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  45399. this._useCtrlForPanning = useCtrlForPanning;
  45400. this._panningMouseButton = panningMouseButton;
  45401. this.inputs.attachElement(element, noPreventDefault);
  45402. this._reset = function () {
  45403. _this.inertialAlphaOffset = 0;
  45404. _this.inertialBetaOffset = 0;
  45405. _this.inertialRadiusOffset = 0;
  45406. _this.inertialPanningX = 0;
  45407. _this.inertialPanningY = 0;
  45408. };
  45409. };
  45410. ArcRotateCamera.prototype.detachControl = function (element) {
  45411. this.inputs.detachElement(element);
  45412. if (this._reset) {
  45413. this._reset();
  45414. }
  45415. };
  45416. ArcRotateCamera.prototype._checkInputs = function () {
  45417. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  45418. if (this._collisionTriggered) {
  45419. return;
  45420. }
  45421. this.inputs.checkInputs();
  45422. // Inertia
  45423. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  45424. if (this.getScene().useRightHandedSystem) {
  45425. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  45426. }
  45427. else {
  45428. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  45429. }
  45430. this.beta += this.inertialBetaOffset;
  45431. this.radius -= this.inertialRadiusOffset;
  45432. this.inertialAlphaOffset *= this.inertia;
  45433. this.inertialBetaOffset *= this.inertia;
  45434. this.inertialRadiusOffset *= this.inertia;
  45435. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  45436. this.inertialAlphaOffset = 0;
  45437. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  45438. this.inertialBetaOffset = 0;
  45439. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  45440. this.inertialRadiusOffset = 0;
  45441. }
  45442. // Panning inertia
  45443. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  45444. if (!this._localDirection) {
  45445. this._localDirection = BABYLON.Vector3.Zero();
  45446. this._transformedDirection = BABYLON.Vector3.Zero();
  45447. }
  45448. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  45449. this._localDirection.multiplyInPlace(this.panningAxis);
  45450. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  45451. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  45452. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  45453. if (!this.panningAxis.y) {
  45454. this._transformedDirection.y = 0;
  45455. }
  45456. if (!this._targetHost) {
  45457. if (this.panningDistanceLimit) {
  45458. this._transformedDirection.addInPlace(this._target);
  45459. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  45460. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  45461. this._target.copyFrom(this._transformedDirection);
  45462. }
  45463. }
  45464. else {
  45465. this._target.addInPlace(this._transformedDirection);
  45466. }
  45467. }
  45468. this.inertialPanningX *= this.panningInertia;
  45469. this.inertialPanningY *= this.panningInertia;
  45470. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  45471. this.inertialPanningX = 0;
  45472. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  45473. this.inertialPanningY = 0;
  45474. }
  45475. // Limits
  45476. this._checkLimits();
  45477. _super.prototype._checkInputs.call(this);
  45478. };
  45479. ArcRotateCamera.prototype._checkLimits = function () {
  45480. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  45481. if (this.allowUpsideDown && this.beta > Math.PI) {
  45482. this.beta = this.beta - (2 * Math.PI);
  45483. }
  45484. }
  45485. else {
  45486. if (this.beta < this.lowerBetaLimit) {
  45487. this.beta = this.lowerBetaLimit;
  45488. }
  45489. }
  45490. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  45491. if (this.allowUpsideDown && this.beta < -Math.PI) {
  45492. this.beta = this.beta + (2 * Math.PI);
  45493. }
  45494. }
  45495. else {
  45496. if (this.beta > this.upperBetaLimit) {
  45497. this.beta = this.upperBetaLimit;
  45498. }
  45499. }
  45500. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  45501. this.alpha = this.lowerAlphaLimit;
  45502. }
  45503. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  45504. this.alpha = this.upperAlphaLimit;
  45505. }
  45506. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  45507. this.radius = this.lowerRadiusLimit;
  45508. }
  45509. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  45510. this.radius = this.upperRadiusLimit;
  45511. }
  45512. };
  45513. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  45514. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  45515. this.radius = this._computationVector.length();
  45516. if (this.radius === 0) {
  45517. this.radius = 0.0001; // Just to avoid division by zero
  45518. }
  45519. // Alpha
  45520. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  45521. if (this._computationVector.z < 0) {
  45522. this.alpha = 2 * Math.PI - this.alpha;
  45523. }
  45524. // Beta
  45525. this.beta = Math.acos(this._computationVector.y / this.radius);
  45526. this._checkLimits();
  45527. };
  45528. ArcRotateCamera.prototype.setPosition = function (position) {
  45529. if (this.position.equals(position)) {
  45530. return;
  45531. }
  45532. this.position.copyFrom(position);
  45533. this.rebuildAnglesAndRadius();
  45534. };
  45535. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  45536. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  45537. if (allowSamePosition === void 0) { allowSamePosition = false; }
  45538. if (target.getBoundingInfo) {
  45539. if (toBoundingCenter) {
  45540. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  45541. }
  45542. else {
  45543. this._targetBoundingCenter = null;
  45544. }
  45545. this._targetHost = target;
  45546. this._target = this._getTargetPosition();
  45547. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  45548. }
  45549. else {
  45550. var newTarget = target;
  45551. var currentTarget = this._getTargetPosition();
  45552. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  45553. return;
  45554. }
  45555. this._targetHost = null;
  45556. this._target = newTarget;
  45557. this._targetBoundingCenter = null;
  45558. this.onMeshTargetChangedObservable.notifyObservers(null);
  45559. }
  45560. this.rebuildAnglesAndRadius();
  45561. };
  45562. ArcRotateCamera.prototype._getViewMatrix = function () {
  45563. // Compute
  45564. var cosa = Math.cos(this.alpha);
  45565. var sina = Math.sin(this.alpha);
  45566. var cosb = Math.cos(this.beta);
  45567. var sinb = Math.sin(this.beta);
  45568. if (sinb === 0) {
  45569. sinb = 0.0001;
  45570. }
  45571. var target = this._getTargetPosition();
  45572. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  45573. target.addToRef(this._computationVector, this._newPosition);
  45574. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  45575. if (!this._collider) {
  45576. this._collider = new BABYLON.Collider();
  45577. }
  45578. this._collider._radius = this.collisionRadius;
  45579. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  45580. this._collisionTriggered = true;
  45581. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  45582. }
  45583. else {
  45584. this.position.copyFrom(this._newPosition);
  45585. var up = this.upVector;
  45586. if (this.allowUpsideDown && sinb < 0) {
  45587. up = up.clone();
  45588. up = up.negate();
  45589. }
  45590. if (this.getScene().useRightHandedSystem) {
  45591. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  45592. }
  45593. else {
  45594. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  45595. }
  45596. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  45597. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  45598. }
  45599. this._currentTarget = target;
  45600. return this._viewMatrix;
  45601. };
  45602. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  45603. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45604. meshes = meshes || this.getScene().meshes;
  45605. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  45606. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  45607. this.radius = distance * this.zoomOnFactor;
  45608. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  45609. };
  45610. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  45611. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  45612. var meshesOrMinMaxVector;
  45613. var distance;
  45614. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  45615. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  45616. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  45617. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  45618. }
  45619. else {
  45620. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  45621. meshesOrMinMaxVector = minMaxVectorAndDistance;
  45622. distance = minMaxVectorAndDistance.distance;
  45623. }
  45624. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  45625. if (!doNotUpdateMaxZ) {
  45626. this.maxZ = distance * 2;
  45627. }
  45628. };
  45629. /**
  45630. * @override
  45631. * Override Camera.createRigCamera
  45632. */
  45633. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  45634. var alphaShift = 0;
  45635. switch (this.cameraRigMode) {
  45636. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45637. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45638. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45639. case BABYLON.Camera.RIG_MODE_VR:
  45640. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  45641. break;
  45642. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45643. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  45644. break;
  45645. }
  45646. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  45647. rigCam._cameraRigParams = {};
  45648. return rigCam;
  45649. };
  45650. /**
  45651. * @override
  45652. * Override Camera._updateRigCameras
  45653. */
  45654. ArcRotateCamera.prototype._updateRigCameras = function () {
  45655. var camLeft = this._rigCameras[0];
  45656. var camRight = this._rigCameras[1];
  45657. camLeft.beta = camRight.beta = this.beta;
  45658. camLeft.radius = camRight.radius = this.radius;
  45659. switch (this.cameraRigMode) {
  45660. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  45661. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  45662. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  45663. case BABYLON.Camera.RIG_MODE_VR:
  45664. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45665. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45666. break;
  45667. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  45668. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  45669. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  45670. break;
  45671. }
  45672. _super.prototype._updateRigCameras.call(this);
  45673. };
  45674. ArcRotateCamera.prototype.dispose = function () {
  45675. this.inputs.clear();
  45676. _super.prototype.dispose.call(this);
  45677. };
  45678. ArcRotateCamera.prototype.getClassName = function () {
  45679. return "ArcRotateCamera";
  45680. };
  45681. __decorate([
  45682. BABYLON.serialize()
  45683. ], ArcRotateCamera.prototype, "alpha", void 0);
  45684. __decorate([
  45685. BABYLON.serialize()
  45686. ], ArcRotateCamera.prototype, "beta", void 0);
  45687. __decorate([
  45688. BABYLON.serialize()
  45689. ], ArcRotateCamera.prototype, "radius", void 0);
  45690. __decorate([
  45691. BABYLON.serializeAsVector3("target")
  45692. ], ArcRotateCamera.prototype, "_target", void 0);
  45693. __decorate([
  45694. BABYLON.serialize()
  45695. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  45696. __decorate([
  45697. BABYLON.serialize()
  45698. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  45699. __decorate([
  45700. BABYLON.serialize()
  45701. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  45702. __decorate([
  45703. BABYLON.serialize()
  45704. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  45705. __decorate([
  45706. BABYLON.serialize()
  45707. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  45708. __decorate([
  45709. BABYLON.serialize()
  45710. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  45711. __decorate([
  45712. BABYLON.serialize()
  45713. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  45714. __decorate([
  45715. BABYLON.serialize()
  45716. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  45717. __decorate([
  45718. BABYLON.serialize()
  45719. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  45720. __decorate([
  45721. BABYLON.serialize()
  45722. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  45723. __decorate([
  45724. BABYLON.serialize()
  45725. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  45726. __decorate([
  45727. BABYLON.serialize()
  45728. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  45729. __decorate([
  45730. BABYLON.serialize()
  45731. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  45732. __decorate([
  45733. BABYLON.serializeAsVector3()
  45734. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  45735. __decorate([
  45736. BABYLON.serialize()
  45737. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  45738. __decorate([
  45739. BABYLON.serialize()
  45740. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  45741. __decorate([
  45742. BABYLON.serialize()
  45743. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  45744. return ArcRotateCamera;
  45745. }(BABYLON.TargetCamera));
  45746. BABYLON.ArcRotateCamera = ArcRotateCamera;
  45747. })(BABYLON || (BABYLON = {}));
  45748. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  45749. "use strict";
  45750. var BABYLON;
  45751. (function (BABYLON) {
  45752. /**
  45753. * The HemisphericLight simulates the ambient environment light,
  45754. * so the passed direction is the light reflection direction, not the incoming direction.
  45755. */
  45756. var HemisphericLight = /** @class */ (function (_super) {
  45757. __extends(HemisphericLight, _super);
  45758. /**
  45759. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  45760. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  45761. * The HemisphericLight can't cast shadows.
  45762. * Documentation : http://doc.babylonjs.com/tutorials/lights
  45763. * @param name The friendly name of the light
  45764. * @param direction The direction of the light reflection
  45765. * @param scene The scene the light belongs to
  45766. */
  45767. function HemisphericLight(name, direction, scene) {
  45768. var _this = _super.call(this, name, scene) || this;
  45769. /**
  45770. * The groundColor is the light in the opposite direction to the one specified during creation.
  45771. * 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.
  45772. */
  45773. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  45774. _this.direction = direction || BABYLON.Vector3.Up();
  45775. return _this;
  45776. }
  45777. HemisphericLight.prototype._buildUniformLayout = function () {
  45778. this._uniformBuffer.addUniform("vLightData", 4);
  45779. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  45780. this._uniformBuffer.addUniform("vLightSpecular", 3);
  45781. this._uniformBuffer.addUniform("vLightGround", 3);
  45782. this._uniformBuffer.addUniform("shadowsInfo", 3);
  45783. this._uniformBuffer.addUniform("depthValues", 2);
  45784. this._uniformBuffer.create();
  45785. };
  45786. /**
  45787. * Returns the string "HemisphericLight".
  45788. * @return The class name
  45789. */
  45790. HemisphericLight.prototype.getClassName = function () {
  45791. return "HemisphericLight";
  45792. };
  45793. /**
  45794. * Sets the HemisphericLight direction towards the passed target (Vector3).
  45795. * Returns the updated direction.
  45796. * @param target The target the direction should point to
  45797. * @return The computed direction
  45798. */
  45799. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  45800. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  45801. return this.direction;
  45802. };
  45803. /**
  45804. * Returns the shadow generator associated to the light.
  45805. * @returns Always null for hemispheric lights because it does not support shadows.
  45806. */
  45807. HemisphericLight.prototype.getShadowGenerator = function () {
  45808. return null;
  45809. };
  45810. /**
  45811. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  45812. * @param effect The effect to update
  45813. * @param lightIndex The index of the light in the effect to update
  45814. * @returns The hemispheric light
  45815. */
  45816. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  45817. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  45818. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  45819. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  45820. return this;
  45821. };
  45822. /**
  45823. * @ignore internal use only.
  45824. */
  45825. HemisphericLight.prototype._getWorldMatrix = function () {
  45826. if (!this._worldMatrix) {
  45827. this._worldMatrix = BABYLON.Matrix.Identity();
  45828. }
  45829. return this._worldMatrix;
  45830. };
  45831. /**
  45832. * Returns the integer 3.
  45833. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  45834. */
  45835. HemisphericLight.prototype.getTypeID = function () {
  45836. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  45837. };
  45838. __decorate([
  45839. BABYLON.serializeAsColor3()
  45840. ], HemisphericLight.prototype, "groundColor", void 0);
  45841. __decorate([
  45842. BABYLON.serializeAsVector3()
  45843. ], HemisphericLight.prototype, "direction", void 0);
  45844. return HemisphericLight;
  45845. }(BABYLON.Light));
  45846. BABYLON.HemisphericLight = HemisphericLight;
  45847. })(BABYLON || (BABYLON = {}));
  45848. //# sourceMappingURL=babylon.hemisphericLight.js.map
  45849. "use strict";
  45850. var BABYLON;
  45851. (function (BABYLON) {
  45852. /**
  45853. * Base implementation of @see IShadowLight
  45854. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  45855. */
  45856. var ShadowLight = /** @class */ (function (_super) {
  45857. __extends(ShadowLight, _super);
  45858. function ShadowLight() {
  45859. var _this = _super !== null && _super.apply(this, arguments) || this;
  45860. _this._needProjectionMatrixCompute = true;
  45861. return _this;
  45862. }
  45863. ShadowLight.prototype._setPosition = function (value) {
  45864. this._position = value;
  45865. };
  45866. Object.defineProperty(ShadowLight.prototype, "position", {
  45867. /**
  45868. * Sets the position the shadow will be casted from. Also use as the light position for both
  45869. * point and spot lights.
  45870. */
  45871. get: function () {
  45872. return this._position;
  45873. },
  45874. /**
  45875. * Sets the position the shadow will be casted from. Also use as the light position for both
  45876. * point and spot lights.
  45877. */
  45878. set: function (value) {
  45879. this._setPosition(value);
  45880. },
  45881. enumerable: true,
  45882. configurable: true
  45883. });
  45884. ShadowLight.prototype._setDirection = function (value) {
  45885. this._direction = value;
  45886. };
  45887. Object.defineProperty(ShadowLight.prototype, "direction", {
  45888. /**
  45889. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  45890. * Also use as the light direction on spot and directional lights.
  45891. */
  45892. get: function () {
  45893. return this._direction;
  45894. },
  45895. /**
  45896. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  45897. * Also use as the light direction on spot and directional lights.
  45898. */
  45899. set: function (value) {
  45900. this._setDirection(value);
  45901. },
  45902. enumerable: true,
  45903. configurable: true
  45904. });
  45905. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  45906. /**
  45907. * Gets the shadow projection clipping minimum z value.
  45908. */
  45909. get: function () {
  45910. return this._shadowMinZ;
  45911. },
  45912. /**
  45913. * Sets the shadow projection clipping minimum z value.
  45914. */
  45915. set: function (value) {
  45916. this._shadowMinZ = value;
  45917. this.forceProjectionMatrixCompute();
  45918. },
  45919. enumerable: true,
  45920. configurable: true
  45921. });
  45922. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  45923. /**
  45924. * Sets the shadow projection clipping maximum z value.
  45925. */
  45926. get: function () {
  45927. return this._shadowMaxZ;
  45928. },
  45929. /**
  45930. * Gets the shadow projection clipping maximum z value.
  45931. */
  45932. set: function (value) {
  45933. this._shadowMaxZ = value;
  45934. this.forceProjectionMatrixCompute();
  45935. },
  45936. enumerable: true,
  45937. configurable: true
  45938. });
  45939. /**
  45940. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  45941. * @returns true if the information has been computed, false if it does not need to (no parenting)
  45942. */
  45943. ShadowLight.prototype.computeTransformedInformation = function () {
  45944. if (this.parent && this.parent.getWorldMatrix) {
  45945. if (!this.transformedPosition) {
  45946. this.transformedPosition = BABYLON.Vector3.Zero();
  45947. }
  45948. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  45949. // In case the direction is present.
  45950. if (this.direction) {
  45951. if (!this.transformedDirection) {
  45952. this.transformedDirection = BABYLON.Vector3.Zero();
  45953. }
  45954. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  45955. }
  45956. return true;
  45957. }
  45958. return false;
  45959. };
  45960. /**
  45961. * Return the depth scale used for the shadow map.
  45962. * @returns the depth scale.
  45963. */
  45964. ShadowLight.prototype.getDepthScale = function () {
  45965. return 50.0;
  45966. };
  45967. /**
  45968. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  45969. * @param faceIndex The index of the face we are computed the direction to generate shadow
  45970. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  45971. */
  45972. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  45973. return this.transformedDirection ? this.transformedDirection : this.direction;
  45974. };
  45975. /**
  45976. * Returns the ShadowLight absolute position in the World.
  45977. * @returns the position vector in world space
  45978. */
  45979. ShadowLight.prototype.getAbsolutePosition = function () {
  45980. return this.transformedPosition ? this.transformedPosition : this.position;
  45981. };
  45982. /**
  45983. * Sets the ShadowLight direction toward the passed target.
  45984. * @param target The point tot target in local space
  45985. * @returns the updated ShadowLight direction
  45986. */
  45987. ShadowLight.prototype.setDirectionToTarget = function (target) {
  45988. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  45989. return this.direction;
  45990. };
  45991. /**
  45992. * Returns the light rotation in euler definition.
  45993. * @returns the x y z rotation in local space.
  45994. */
  45995. ShadowLight.prototype.getRotation = function () {
  45996. this.direction.normalize();
  45997. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  45998. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  45999. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  46000. };
  46001. /**
  46002. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  46003. * @returns true if a cube texture needs to be use
  46004. */
  46005. ShadowLight.prototype.needCube = function () {
  46006. return false;
  46007. };
  46008. /**
  46009. * Detects if the projection matrix requires to be recomputed this frame.
  46010. * @returns true if it requires to be recomputed otherwise, false.
  46011. */
  46012. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  46013. return this._needProjectionMatrixCompute;
  46014. };
  46015. /**
  46016. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  46017. */
  46018. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  46019. this._needProjectionMatrixCompute = true;
  46020. };
  46021. /**
  46022. * Get the world matrix of the sahdow lights.
  46023. * @ignore Internal Use Only
  46024. */
  46025. ShadowLight.prototype._getWorldMatrix = function () {
  46026. if (!this._worldMatrix) {
  46027. this._worldMatrix = BABYLON.Matrix.Identity();
  46028. }
  46029. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  46030. return this._worldMatrix;
  46031. };
  46032. /**
  46033. * Gets the minZ used for shadow according to both the scene and the light.
  46034. * @param activeCamera The camera we are returning the min for
  46035. * @returns the depth min z
  46036. */
  46037. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  46038. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  46039. };
  46040. /**
  46041. * Gets the maxZ used for shadow according to both the scene and the light.
  46042. * @param activeCamera The camera we are returning the max for
  46043. * @returns the depth max z
  46044. */
  46045. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  46046. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  46047. };
  46048. /**
  46049. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  46050. * @param matrix The materix to updated with the projection information
  46051. * @param viewMatrix The transform matrix of the light
  46052. * @param renderList The list of mesh to render in the map
  46053. * @returns The current light
  46054. */
  46055. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46056. if (this.customProjectionMatrixBuilder) {
  46057. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  46058. }
  46059. else {
  46060. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  46061. }
  46062. return this;
  46063. };
  46064. __decorate([
  46065. BABYLON.serializeAsVector3()
  46066. ], ShadowLight.prototype, "position", null);
  46067. __decorate([
  46068. BABYLON.serializeAsVector3()
  46069. ], ShadowLight.prototype, "direction", null);
  46070. __decorate([
  46071. BABYLON.serialize()
  46072. ], ShadowLight.prototype, "shadowMinZ", null);
  46073. __decorate([
  46074. BABYLON.serialize()
  46075. ], ShadowLight.prototype, "shadowMaxZ", null);
  46076. return ShadowLight;
  46077. }(BABYLON.Light));
  46078. BABYLON.ShadowLight = ShadowLight;
  46079. })(BABYLON || (BABYLON = {}));
  46080. //# sourceMappingURL=babylon.shadowLight.js.map
  46081. "use strict";
  46082. var BABYLON;
  46083. (function (BABYLON) {
  46084. /**
  46085. * A point light is a light defined by an unique point in world space.
  46086. * The light is emitted in every direction from this point.
  46087. * A good example of a point light is a standard light bulb.
  46088. * Documentation: https://doc.babylonjs.com/babylon101/lights
  46089. */
  46090. var PointLight = /** @class */ (function (_super) {
  46091. __extends(PointLight, _super);
  46092. /**
  46093. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  46094. * A PointLight emits the light in every direction.
  46095. * It can cast shadows.
  46096. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  46097. * ```javascript
  46098. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  46099. * ```
  46100. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46101. * @param name The light friendly name
  46102. * @param position The position of the point light in the scene
  46103. * @param scene The scene the lights belongs to
  46104. */
  46105. function PointLight(name, position, scene) {
  46106. var _this = _super.call(this, name, scene) || this;
  46107. _this._shadowAngle = Math.PI / 2;
  46108. _this.position = position;
  46109. return _this;
  46110. }
  46111. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  46112. /**
  46113. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46114. * This specifies what angle the shadow will use to be created.
  46115. *
  46116. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  46117. */
  46118. get: function () {
  46119. return this._shadowAngle;
  46120. },
  46121. /**
  46122. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46123. * This specifies what angle the shadow will use to be created.
  46124. *
  46125. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  46126. */
  46127. set: function (value) {
  46128. this._shadowAngle = value;
  46129. this.forceProjectionMatrixCompute();
  46130. },
  46131. enumerable: true,
  46132. configurable: true
  46133. });
  46134. Object.defineProperty(PointLight.prototype, "direction", {
  46135. /**
  46136. * Gets the direction if it has been set.
  46137. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46138. */
  46139. get: function () {
  46140. return this._direction;
  46141. },
  46142. /**
  46143. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  46144. */
  46145. set: function (value) {
  46146. var previousNeedCube = this.needCube();
  46147. this._direction = value;
  46148. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  46149. this._shadowGenerator.recreateShadowMap();
  46150. }
  46151. },
  46152. enumerable: true,
  46153. configurable: true
  46154. });
  46155. /**
  46156. * Returns the string "PointLight"
  46157. * @returns the class name
  46158. */
  46159. PointLight.prototype.getClassName = function () {
  46160. return "PointLight";
  46161. };
  46162. /**
  46163. * Returns the integer 0.
  46164. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46165. */
  46166. PointLight.prototype.getTypeID = function () {
  46167. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  46168. };
  46169. /**
  46170. * Specifies wether or not the shadowmap should be a cube texture.
  46171. * @returns true if the shadowmap needs to be a cube texture.
  46172. */
  46173. PointLight.prototype.needCube = function () {
  46174. return !this.direction;
  46175. };
  46176. /**
  46177. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  46178. * @param faceIndex The index of the face we are computed the direction to generate shadow
  46179. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  46180. */
  46181. PointLight.prototype.getShadowDirection = function (faceIndex) {
  46182. if (this.direction) {
  46183. return _super.prototype.getShadowDirection.call(this, faceIndex);
  46184. }
  46185. else {
  46186. switch (faceIndex) {
  46187. case 0:
  46188. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  46189. case 1:
  46190. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  46191. case 2:
  46192. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  46193. case 3:
  46194. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  46195. case 4:
  46196. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  46197. case 5:
  46198. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  46199. }
  46200. }
  46201. return BABYLON.Vector3.Zero();
  46202. };
  46203. /**
  46204. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  46205. * - fov = PI / 2
  46206. * - aspect ratio : 1.0
  46207. * - z-near and far equal to the active camera minZ and maxZ.
  46208. * Returns the PointLight.
  46209. */
  46210. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46211. var activeCamera = this.getScene().activeCamera;
  46212. if (!activeCamera) {
  46213. return;
  46214. }
  46215. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  46216. };
  46217. PointLight.prototype._buildUniformLayout = function () {
  46218. this._uniformBuffer.addUniform("vLightData", 4);
  46219. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46220. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46221. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46222. this._uniformBuffer.addUniform("depthValues", 2);
  46223. this._uniformBuffer.create();
  46224. };
  46225. /**
  46226. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  46227. * @param effect The effect to update
  46228. * @param lightIndex The index of the light in the effect to update
  46229. * @returns The point light
  46230. */
  46231. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  46232. if (this.computeTransformedInformation()) {
  46233. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  46234. return this;
  46235. }
  46236. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  46237. return this;
  46238. };
  46239. __decorate([
  46240. BABYLON.serialize()
  46241. ], PointLight.prototype, "shadowAngle", null);
  46242. return PointLight;
  46243. }(BABYLON.ShadowLight));
  46244. BABYLON.PointLight = PointLight;
  46245. })(BABYLON || (BABYLON = {}));
  46246. //# sourceMappingURL=babylon.pointLight.js.map
  46247. "use strict";
  46248. var BABYLON;
  46249. (function (BABYLON) {
  46250. /**
  46251. * A directional light is defined by a direction (what a surprise!).
  46252. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  46253. * 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.
  46254. * Documentation: https://doc.babylonjs.com/babylon101/lights
  46255. */
  46256. var DirectionalLight = /** @class */ (function (_super) {
  46257. __extends(DirectionalLight, _super);
  46258. /**
  46259. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  46260. * The directional light is emitted from everywhere in the given direction.
  46261. * It can cast shawdows.
  46262. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46263. * @param name The friendly name of the light
  46264. * @param direction The direction of the light
  46265. * @param scene The scene the light belongs to
  46266. */
  46267. function DirectionalLight(name, direction, scene) {
  46268. var _this = _super.call(this, name, scene) || this;
  46269. _this._shadowFrustumSize = 0;
  46270. _this._shadowOrthoScale = 0.1;
  46271. /**
  46272. * Automatically compute the projection matrix to best fit (including all the casters)
  46273. * on each frame.
  46274. */
  46275. _this.autoUpdateExtends = true;
  46276. // Cache
  46277. _this._orthoLeft = Number.MAX_VALUE;
  46278. _this._orthoRight = Number.MIN_VALUE;
  46279. _this._orthoTop = Number.MIN_VALUE;
  46280. _this._orthoBottom = Number.MAX_VALUE;
  46281. _this.position = direction.scale(-1.0);
  46282. _this.direction = direction;
  46283. return _this;
  46284. }
  46285. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  46286. /**
  46287. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  46288. */
  46289. get: function () {
  46290. return this._shadowFrustumSize;
  46291. },
  46292. /**
  46293. * Specifies a fix frustum size for the shadow generation.
  46294. */
  46295. set: function (value) {
  46296. this._shadowFrustumSize = value;
  46297. this.forceProjectionMatrixCompute();
  46298. },
  46299. enumerable: true,
  46300. configurable: true
  46301. });
  46302. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  46303. /**
  46304. * Gets the shadow projection scale against the optimal computed one.
  46305. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  46306. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  46307. */
  46308. get: function () {
  46309. return this._shadowOrthoScale;
  46310. },
  46311. /**
  46312. * Sets the shadow projection scale against the optimal computed one.
  46313. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  46314. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  46315. */
  46316. set: function (value) {
  46317. this._shadowOrthoScale = value;
  46318. this.forceProjectionMatrixCompute();
  46319. },
  46320. enumerable: true,
  46321. configurable: true
  46322. });
  46323. /**
  46324. * Returns the string "DirectionalLight".
  46325. * @return The class name
  46326. */
  46327. DirectionalLight.prototype.getClassName = function () {
  46328. return "DirectionalLight";
  46329. };
  46330. /**
  46331. * Returns the integer 1.
  46332. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46333. */
  46334. DirectionalLight.prototype.getTypeID = function () {
  46335. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  46336. };
  46337. /**
  46338. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  46339. * Returns the DirectionalLight Shadow projection matrix.
  46340. */
  46341. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46342. if (this.shadowFrustumSize > 0) {
  46343. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  46344. }
  46345. else {
  46346. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  46347. }
  46348. };
  46349. /**
  46350. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  46351. * Returns the DirectionalLight Shadow projection matrix.
  46352. */
  46353. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  46354. var activeCamera = this.getScene().activeCamera;
  46355. if (!activeCamera) {
  46356. return;
  46357. }
  46358. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  46359. };
  46360. /**
  46361. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  46362. * Returns the DirectionalLight Shadow projection matrix.
  46363. */
  46364. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46365. var activeCamera = this.getScene().activeCamera;
  46366. if (!activeCamera) {
  46367. return;
  46368. }
  46369. // Check extends
  46370. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  46371. var tempVector3 = BABYLON.Vector3.Zero();
  46372. this._orthoLeft = Number.MAX_VALUE;
  46373. this._orthoRight = Number.MIN_VALUE;
  46374. this._orthoTop = Number.MIN_VALUE;
  46375. this._orthoBottom = Number.MAX_VALUE;
  46376. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  46377. var mesh = renderList[meshIndex];
  46378. if (!mesh) {
  46379. continue;
  46380. }
  46381. var boundingInfo = mesh.getBoundingInfo();
  46382. var boundingBox = boundingInfo.boundingBox;
  46383. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  46384. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  46385. if (tempVector3.x < this._orthoLeft)
  46386. this._orthoLeft = tempVector3.x;
  46387. if (tempVector3.y < this._orthoBottom)
  46388. this._orthoBottom = tempVector3.y;
  46389. if (tempVector3.x > this._orthoRight)
  46390. this._orthoRight = tempVector3.x;
  46391. if (tempVector3.y > this._orthoTop)
  46392. this._orthoTop = tempVector3.y;
  46393. }
  46394. }
  46395. }
  46396. var xOffset = this._orthoRight - this._orthoLeft;
  46397. var yOffset = this._orthoTop - this._orthoBottom;
  46398. 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);
  46399. };
  46400. DirectionalLight.prototype._buildUniformLayout = function () {
  46401. this._uniformBuffer.addUniform("vLightData", 4);
  46402. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46403. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46404. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46405. this._uniformBuffer.addUniform("depthValues", 2);
  46406. this._uniformBuffer.create();
  46407. };
  46408. /**
  46409. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  46410. * @param effect The effect to update
  46411. * @param lightIndex The index of the light in the effect to update
  46412. * @returns The directional light
  46413. */
  46414. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  46415. if (this.computeTransformedInformation()) {
  46416. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  46417. return this;
  46418. }
  46419. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  46420. return this;
  46421. };
  46422. /**
  46423. * Gets the minZ used for shadow according to both the scene and the light.
  46424. *
  46425. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  46426. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  46427. * @param activeCamera The camera we are returning the min for
  46428. * @returns the depth min z
  46429. */
  46430. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  46431. return 1;
  46432. };
  46433. /**
  46434. * Gets the maxZ used for shadow according to both the scene and the light.
  46435. *
  46436. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  46437. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  46438. * @param activeCamera The camera we are returning the max for
  46439. * @returns the depth max z
  46440. */
  46441. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  46442. return 1;
  46443. };
  46444. __decorate([
  46445. BABYLON.serialize()
  46446. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  46447. __decorate([
  46448. BABYLON.serialize()
  46449. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  46450. __decorate([
  46451. BABYLON.serialize()
  46452. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  46453. return DirectionalLight;
  46454. }(BABYLON.ShadowLight));
  46455. BABYLON.DirectionalLight = DirectionalLight;
  46456. })(BABYLON || (BABYLON = {}));
  46457. //# sourceMappingURL=babylon.directionalLight.js.map
  46458. "use strict";
  46459. var BABYLON;
  46460. (function (BABYLON) {
  46461. /**
  46462. * A spot light is defined by a position, a direction, an angle, and an exponent.
  46463. * These values define a cone of light starting from the position, emitting toward the direction.
  46464. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  46465. * and the exponent defines the speed of the decay of the light with distance (reach).
  46466. * Documentation: https://doc.babylonjs.com/babylon101/lights
  46467. */
  46468. var SpotLight = /** @class */ (function (_super) {
  46469. __extends(SpotLight, _super);
  46470. /**
  46471. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  46472. * It can cast shadows.
  46473. * Documentation : http://doc.babylonjs.com/tutorials/lights
  46474. * @param name The light friendly name
  46475. * @param position The position of the spot light in the scene
  46476. * @param direction The direction of the light in the scene
  46477. * @param angle The cone angle of the light in Radians
  46478. * @param exponent The light decay speed with the distance from the emission spot
  46479. * @param scene The scene the lights belongs to
  46480. */
  46481. function SpotLight(name, position, direction, angle, exponent, scene) {
  46482. var _this = _super.call(this, name, scene) || this;
  46483. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  46484. _this._projectionTextureLightNear = 1e-6;
  46485. _this._projectionTextureLightFar = 1000.0;
  46486. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  46487. _this._projectionTextureViewLightDirty = true;
  46488. _this._projectionTextureProjectionLightDirty = true;
  46489. _this._projectionTextureDirty = true;
  46490. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  46491. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  46492. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  46493. _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);
  46494. _this.position = position;
  46495. _this.direction = direction;
  46496. _this.angle = angle;
  46497. _this.exponent = exponent;
  46498. return _this;
  46499. }
  46500. Object.defineProperty(SpotLight.prototype, "angle", {
  46501. /**
  46502. * Gets the cone angle of the spot light in Radians.
  46503. */
  46504. get: function () {
  46505. return this._angle;
  46506. },
  46507. /**
  46508. * Sets the cone angle of the spot light in Radians.
  46509. */
  46510. set: function (value) {
  46511. this._angle = value;
  46512. this._projectionTextureProjectionLightDirty = true;
  46513. this.forceProjectionMatrixCompute();
  46514. },
  46515. enumerable: true,
  46516. configurable: true
  46517. });
  46518. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  46519. /**
  46520. * Allows scaling the angle of the light for shadow generation only.
  46521. */
  46522. get: function () {
  46523. return this._shadowAngleScale;
  46524. },
  46525. /**
  46526. * Allows scaling the angle of the light for shadow generation only.
  46527. */
  46528. set: function (value) {
  46529. this._shadowAngleScale = value;
  46530. this.forceProjectionMatrixCompute();
  46531. },
  46532. enumerable: true,
  46533. configurable: true
  46534. });
  46535. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  46536. /**
  46537. * Allows reading the projecton texture
  46538. */
  46539. get: function () {
  46540. return this._projectionTextureMatrix;
  46541. },
  46542. enumerable: true,
  46543. configurable: true
  46544. });
  46545. ;
  46546. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  46547. /**
  46548. * Gets the near clip of the Spotlight for texture projection.
  46549. */
  46550. get: function () {
  46551. return this._projectionTextureLightNear;
  46552. },
  46553. /**
  46554. * Sets the near clip of the Spotlight for texture projection.
  46555. */
  46556. set: function (value) {
  46557. this._projectionTextureLightNear = value;
  46558. this._projectionTextureProjectionLightDirty = true;
  46559. },
  46560. enumerable: true,
  46561. configurable: true
  46562. });
  46563. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  46564. /**
  46565. * Gets the far clip of the Spotlight for texture projection.
  46566. */
  46567. get: function () {
  46568. return this._projectionTextureLightFar;
  46569. },
  46570. /**
  46571. * Sets the far clip of the Spotlight for texture projection.
  46572. */
  46573. set: function (value) {
  46574. this._projectionTextureLightFar = value;
  46575. this._projectionTextureProjectionLightDirty = true;
  46576. },
  46577. enumerable: true,
  46578. configurable: true
  46579. });
  46580. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  46581. /**
  46582. * Gets the Up vector of the Spotlight for texture projection.
  46583. */
  46584. get: function () {
  46585. return this._projectionTextureUpDirection;
  46586. },
  46587. /**
  46588. * Sets the Up vector of the Spotlight for texture projection.
  46589. */
  46590. set: function (value) {
  46591. this._projectionTextureUpDirection = value;
  46592. this._projectionTextureProjectionLightDirty = true;
  46593. },
  46594. enumerable: true,
  46595. configurable: true
  46596. });
  46597. ;
  46598. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  46599. /**
  46600. * Gets the projection texture of the light.
  46601. */
  46602. get: function () {
  46603. return this._projectionTexture;
  46604. },
  46605. /**
  46606. * Sets the projection texture of the light.
  46607. */
  46608. set: function (value) {
  46609. this._projectionTexture = value;
  46610. this._projectionTextureDirty = true;
  46611. },
  46612. enumerable: true,
  46613. configurable: true
  46614. });
  46615. /**
  46616. * Returns the string "SpotLight".
  46617. * @returns the class name
  46618. */
  46619. SpotLight.prototype.getClassName = function () {
  46620. return "SpotLight";
  46621. };
  46622. /**
  46623. * Returns the integer 2.
  46624. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  46625. */
  46626. SpotLight.prototype.getTypeID = function () {
  46627. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  46628. };
  46629. /**
  46630. * Overrides the direction setter to recompute the projection texture view light Matrix.
  46631. */
  46632. SpotLight.prototype._setDirection = function (value) {
  46633. _super.prototype._setDirection.call(this, value);
  46634. this._projectionTextureViewLightDirty = true;
  46635. };
  46636. /**
  46637. * Overrides the position setter to recompute the projection texture view light Matrix.
  46638. */
  46639. SpotLight.prototype._setPosition = function (value) {
  46640. _super.prototype._setPosition.call(this, value);
  46641. this._projectionTextureViewLightDirty = true;
  46642. };
  46643. /**
  46644. * 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.
  46645. * Returns the SpotLight.
  46646. */
  46647. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  46648. var activeCamera = this.getScene().activeCamera;
  46649. if (!activeCamera) {
  46650. return;
  46651. }
  46652. this._shadowAngleScale = this._shadowAngleScale || 1;
  46653. var angle = this._shadowAngleScale * this._angle;
  46654. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  46655. };
  46656. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  46657. this._projectionTextureViewLightDirty = false;
  46658. this._projectionTextureDirty = true;
  46659. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  46660. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  46661. };
  46662. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  46663. this._projectionTextureProjectionLightDirty = false;
  46664. this._projectionTextureDirty = true;
  46665. var light_far = this.projectionTextureLightFar;
  46666. var light_near = this.projectionTextureLightNear;
  46667. var P = light_far / (light_far - light_near);
  46668. var Q = -P * light_near;
  46669. var S = 1.0 / Math.tan(this._angle / 2.0);
  46670. var A = 1.0;
  46671. 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);
  46672. };
  46673. /**
  46674. * Main function for light texture projection matrix computing.
  46675. */
  46676. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  46677. this._projectionTextureDirty = false;
  46678. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  46679. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  46680. };
  46681. SpotLight.prototype._buildUniformLayout = function () {
  46682. this._uniformBuffer.addUniform("vLightData", 4);
  46683. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  46684. this._uniformBuffer.addUniform("vLightSpecular", 3);
  46685. this._uniformBuffer.addUniform("vLightDirection", 3);
  46686. this._uniformBuffer.addUniform("shadowsInfo", 3);
  46687. this._uniformBuffer.addUniform("depthValues", 2);
  46688. this._uniformBuffer.create();
  46689. };
  46690. /**
  46691. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  46692. * @param effect The effect to update
  46693. * @param lightIndex The index of the light in the effect to update
  46694. * @returns The spot light
  46695. */
  46696. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  46697. var normalizeDirection;
  46698. if (this.computeTransformedInformation()) {
  46699. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  46700. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  46701. }
  46702. else {
  46703. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  46704. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  46705. }
  46706. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  46707. if (this.projectionTexture && this.projectionTexture.isReady()) {
  46708. if (this._projectionTextureViewLightDirty) {
  46709. this._computeProjectionTextureViewLightMatrix();
  46710. }
  46711. if (this._projectionTextureProjectionLightDirty) {
  46712. this._computeProjectionTextureProjectionLightMatrix();
  46713. }
  46714. if (this._projectionTextureDirty) {
  46715. this._computeProjectionTextureMatrix();
  46716. }
  46717. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  46718. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  46719. }
  46720. return this;
  46721. };
  46722. /**
  46723. * Disposes the light and the associated resources.
  46724. */
  46725. SpotLight.prototype.dispose = function () {
  46726. _super.prototype.dispose.call(this);
  46727. if (this._projectionTexture) {
  46728. this._projectionTexture.dispose();
  46729. }
  46730. };
  46731. __decorate([
  46732. BABYLON.serialize()
  46733. ], SpotLight.prototype, "angle", null);
  46734. __decorate([
  46735. BABYLON.serialize()
  46736. ], SpotLight.prototype, "shadowAngleScale", null);
  46737. __decorate([
  46738. BABYLON.serialize()
  46739. ], SpotLight.prototype, "exponent", void 0);
  46740. __decorate([
  46741. BABYLON.serialize()
  46742. ], SpotLight.prototype, "projectionTextureLightNear", null);
  46743. __decorate([
  46744. BABYLON.serialize()
  46745. ], SpotLight.prototype, "projectionTextureLightFar", null);
  46746. __decorate([
  46747. BABYLON.serialize()
  46748. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  46749. __decorate([
  46750. BABYLON.serializeAsTexture("projectedLightTexture")
  46751. ], SpotLight.prototype, "_projectionTexture", void 0);
  46752. return SpotLight;
  46753. }(BABYLON.ShadowLight));
  46754. BABYLON.SpotLight = SpotLight;
  46755. })(BABYLON || (BABYLON = {}));
  46756. //# sourceMappingURL=babylon.spotLight.js.map
  46757. "use strict";
  46758. var BABYLON;
  46759. (function (BABYLON) {
  46760. /**
  46761. * Class used to override all child animations of a given target
  46762. */
  46763. var AnimationPropertiesOverride = /** @class */ (function () {
  46764. function AnimationPropertiesOverride() {
  46765. /**
  46766. * Gets or sets a value indicating if animation blending must be used
  46767. */
  46768. this.enableBlending = false;
  46769. /**
  46770. * Gets or sets the blending speed to use when enableBlending is true
  46771. */
  46772. this.blendingSpeed = 0.01;
  46773. /**
  46774. * Gets or sets the default loop mode to use
  46775. */
  46776. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  46777. }
  46778. return AnimationPropertiesOverride;
  46779. }());
  46780. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  46781. })(BABYLON || (BABYLON = {}));
  46782. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  46783. "use strict";
  46784. var BABYLON;
  46785. (function (BABYLON) {
  46786. var AnimationRange = /** @class */ (function () {
  46787. function AnimationRange(name, from, to) {
  46788. this.name = name;
  46789. this.from = from;
  46790. this.to = to;
  46791. }
  46792. AnimationRange.prototype.clone = function () {
  46793. return new AnimationRange(this.name, this.from, this.to);
  46794. };
  46795. return AnimationRange;
  46796. }());
  46797. BABYLON.AnimationRange = AnimationRange;
  46798. /**
  46799. * Composed of a frame, and an action function
  46800. */
  46801. var AnimationEvent = /** @class */ (function () {
  46802. function AnimationEvent(frame, action, onlyOnce) {
  46803. this.frame = frame;
  46804. this.action = action;
  46805. this.onlyOnce = onlyOnce;
  46806. this.isDone = false;
  46807. }
  46808. return AnimationEvent;
  46809. }());
  46810. BABYLON.AnimationEvent = AnimationEvent;
  46811. var PathCursor = /** @class */ (function () {
  46812. function PathCursor(path) {
  46813. this.path = path;
  46814. this._onchange = new Array();
  46815. this.value = 0;
  46816. this.animations = new Array();
  46817. }
  46818. PathCursor.prototype.getPoint = function () {
  46819. var point = this.path.getPointAtLengthPosition(this.value);
  46820. return new BABYLON.Vector3(point.x, 0, point.y);
  46821. };
  46822. PathCursor.prototype.moveAhead = function (step) {
  46823. if (step === void 0) { step = 0.002; }
  46824. this.move(step);
  46825. return this;
  46826. };
  46827. PathCursor.prototype.moveBack = function (step) {
  46828. if (step === void 0) { step = 0.002; }
  46829. this.move(-step);
  46830. return this;
  46831. };
  46832. PathCursor.prototype.move = function (step) {
  46833. if (Math.abs(step) > 1) {
  46834. throw "step size should be less than 1.";
  46835. }
  46836. this.value += step;
  46837. this.ensureLimits();
  46838. this.raiseOnChange();
  46839. return this;
  46840. };
  46841. PathCursor.prototype.ensureLimits = function () {
  46842. while (this.value > 1) {
  46843. this.value -= 1;
  46844. }
  46845. while (this.value < 0) {
  46846. this.value += 1;
  46847. }
  46848. return this;
  46849. };
  46850. // used by animation engine
  46851. PathCursor.prototype.raiseOnChange = function () {
  46852. var _this = this;
  46853. this._onchange.forEach(function (f) { return f(_this); });
  46854. return this;
  46855. };
  46856. PathCursor.prototype.onchange = function (f) {
  46857. this._onchange.push(f);
  46858. return this;
  46859. };
  46860. return PathCursor;
  46861. }());
  46862. BABYLON.PathCursor = PathCursor;
  46863. var AnimationKeyInterpolation;
  46864. (function (AnimationKeyInterpolation) {
  46865. /**
  46866. * Do not interpolate between keys and use the start key value only. Tangents are ignored.
  46867. */
  46868. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  46869. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  46870. var Animation = /** @class */ (function () {
  46871. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  46872. this.name = name;
  46873. this.targetProperty = targetProperty;
  46874. this.framePerSecond = framePerSecond;
  46875. this.dataType = dataType;
  46876. this.loopMode = loopMode;
  46877. this.enableBlending = enableBlending;
  46878. this._runtimeAnimations = new Array();
  46879. // The set of event that will be linked to this animation
  46880. this._events = new Array();
  46881. this.blendingSpeed = 0.01;
  46882. this._ranges = {};
  46883. this.targetPropertyPath = targetProperty.split(".");
  46884. this.dataType = dataType;
  46885. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  46886. }
  46887. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  46888. var dataType = undefined;
  46889. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  46890. dataType = Animation.ANIMATIONTYPE_FLOAT;
  46891. }
  46892. else if (from instanceof BABYLON.Quaternion) {
  46893. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  46894. }
  46895. else if (from instanceof BABYLON.Vector3) {
  46896. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  46897. }
  46898. else if (from instanceof BABYLON.Vector2) {
  46899. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  46900. }
  46901. else if (from instanceof BABYLON.Color3) {
  46902. dataType = Animation.ANIMATIONTYPE_COLOR3;
  46903. }
  46904. else if (from instanceof BABYLON.Size) {
  46905. dataType = Animation.ANIMATIONTYPE_SIZE;
  46906. }
  46907. if (dataType == undefined) {
  46908. return null;
  46909. }
  46910. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  46911. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  46912. animation.setKeys(keys);
  46913. if (easingFunction !== undefined) {
  46914. animation.setEasingFunction(easingFunction);
  46915. }
  46916. return animation;
  46917. };
  46918. /**
  46919. * Sets up an animation.
  46920. * @param property the property to animate
  46921. * @param animationType the animation type to apply
  46922. * @param easingFunction the easing function used in the animation
  46923. * @returns The created animation
  46924. */
  46925. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  46926. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  46927. animation.setEasingFunction(easingFunction);
  46928. return animation;
  46929. };
  46930. /**
  46931. * Create and start an animation on a node
  46932. * @param {string} name defines the name of the global animation that will be run on all nodes
  46933. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46934. * @param {string} targetProperty defines property to animate
  46935. * @param {number} framePerSecond defines the number of frame per second yo use
  46936. * @param {number} totalFrame defines the number of frames in total
  46937. * @param {any} from defines the initial value
  46938. * @param {any} to defines the final value
  46939. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46940. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46941. * @param onAnimationEnd defines the callback to call when animation end
  46942. * @returns the animatable created for this animation
  46943. */
  46944. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46945. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46946. if (!animation) {
  46947. return null;
  46948. }
  46949. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46950. };
  46951. /**
  46952. * Create and start an animation on a node and its descendants
  46953. * @param {string} name defines the name of the global animation that will be run on all nodes
  46954. * @param {BABYLON.Node} node defines the root node where the animation will take place
  46955. * @param {boolean} directDescendantsOnly if true only direct descendants will be used, if false direct and also indirect (children of children, an so on in a recursive manner) descendants will be used.
  46956. * @param {string} targetProperty defines property to animate
  46957. * @param {number} framePerSecond defines the number of frame per second yo use
  46958. * @param {number} totalFrame defines the number of frames in total
  46959. * @param {any} from defines the initial value
  46960. * @param {any} to defines the final value
  46961. * @param {number} loopMode defines which loop mode you want to use (off by default)
  46962. * @param {BABYLON.EasingFunction} easingFunction defines the easing function to use (linear by default)
  46963. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  46964. * @returns the list of animatables created for all nodes
  46965. * @example https://www.babylonjs-playground.com/#MH0VLI
  46966. */
  46967. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46968. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46969. if (!animation) {
  46970. return null;
  46971. }
  46972. var scene = node.getScene();
  46973. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46974. };
  46975. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  46976. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  46977. if (!animation) {
  46978. return null;
  46979. }
  46980. node.animations.push(animation);
  46981. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  46982. };
  46983. /**
  46984. * Transition property of the Camera to the target Value.
  46985. * @param property The property to transition
  46986. * @param targetValue The target Value of the property
  46987. * @param host The object where the property to animate belongs
  46988. * @param scene Scene used to run the animation
  46989. * @param frameRate Framerate (in frame/s) to use
  46990. * @param transition The transition type we want to use
  46991. * @param duration The duration of the animation, in milliseconds
  46992. * @param onAnimationEnd Call back trigger at the end of the animation.
  46993. */
  46994. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  46995. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  46996. if (duration <= 0) {
  46997. host[property] = targetValue;
  46998. if (onAnimationEnd) {
  46999. onAnimationEnd();
  47000. }
  47001. return null;
  47002. }
  47003. var endFrame = frameRate * (duration / 1000);
  47004. transition.setKeys([{
  47005. frame: 0,
  47006. value: host[property].clone ? host[property].clone() : host[property]
  47007. },
  47008. {
  47009. frame: endFrame,
  47010. value: targetValue
  47011. }]);
  47012. if (!host.animations) {
  47013. host.animations = [];
  47014. }
  47015. host.animations.push(transition);
  47016. var animation = scene.beginAnimation(host, 0, endFrame, false);
  47017. animation.onAnimationEnd = onAnimationEnd;
  47018. return animation;
  47019. };
  47020. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  47021. /**
  47022. * Return the array of runtime animations currently using this animation
  47023. */
  47024. get: function () {
  47025. return this._runtimeAnimations;
  47026. },
  47027. enumerable: true,
  47028. configurable: true
  47029. });
  47030. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  47031. get: function () {
  47032. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  47033. var runtimeAnimation = _a[_i];
  47034. if (!runtimeAnimation.isStopped) {
  47035. return true;
  47036. }
  47037. }
  47038. return false;
  47039. },
  47040. enumerable: true,
  47041. configurable: true
  47042. });
  47043. // Methods
  47044. /**
  47045. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  47046. */
  47047. Animation.prototype.toString = function (fullDetails) {
  47048. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  47049. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  47050. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  47051. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  47052. if (fullDetails) {
  47053. ret += ", Ranges: {";
  47054. var first = true;
  47055. for (var name in this._ranges) {
  47056. if (first) {
  47057. ret += ", ";
  47058. first = false;
  47059. }
  47060. ret += name;
  47061. }
  47062. ret += "}";
  47063. }
  47064. return ret;
  47065. };
  47066. /**
  47067. * Add an event to this animation.
  47068. */
  47069. Animation.prototype.addEvent = function (event) {
  47070. this._events.push(event);
  47071. };
  47072. /**
  47073. * Remove all events found at the given frame
  47074. * @param frame
  47075. */
  47076. Animation.prototype.removeEvents = function (frame) {
  47077. for (var index = 0; index < this._events.length; index++) {
  47078. if (this._events[index].frame === frame) {
  47079. this._events.splice(index, 1);
  47080. index--;
  47081. }
  47082. }
  47083. };
  47084. Animation.prototype.getEvents = function () {
  47085. return this._events;
  47086. };
  47087. Animation.prototype.createRange = function (name, from, to) {
  47088. // check name not already in use; could happen for bones after serialized
  47089. if (!this._ranges[name]) {
  47090. this._ranges[name] = new AnimationRange(name, from, to);
  47091. }
  47092. };
  47093. Animation.prototype.deleteRange = function (name, deleteFrames) {
  47094. if (deleteFrames === void 0) { deleteFrames = true; }
  47095. var range = this._ranges[name];
  47096. if (!range) {
  47097. return;
  47098. }
  47099. if (deleteFrames) {
  47100. var from = range.from;
  47101. var to = range.to;
  47102. // this loop MUST go high to low for multiple splices to work
  47103. for (var key = this._keys.length - 1; key >= 0; key--) {
  47104. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  47105. this._keys.splice(key, 1);
  47106. }
  47107. }
  47108. }
  47109. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  47110. };
  47111. Animation.prototype.getRange = function (name) {
  47112. return this._ranges[name];
  47113. };
  47114. Animation.prototype.getKeys = function () {
  47115. return this._keys;
  47116. };
  47117. Animation.prototype.getHighestFrame = function () {
  47118. var ret = 0;
  47119. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  47120. if (ret < this._keys[key].frame) {
  47121. ret = this._keys[key].frame;
  47122. }
  47123. }
  47124. return ret;
  47125. };
  47126. Animation.prototype.getEasingFunction = function () {
  47127. return this._easingFunction;
  47128. };
  47129. Animation.prototype.setEasingFunction = function (easingFunction) {
  47130. this._easingFunction = easingFunction;
  47131. };
  47132. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  47133. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  47134. };
  47135. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47136. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  47137. };
  47138. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  47139. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  47140. };
  47141. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47142. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  47143. };
  47144. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  47145. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  47146. };
  47147. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47148. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  47149. };
  47150. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  47151. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  47152. };
  47153. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  47154. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  47155. };
  47156. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  47157. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  47158. };
  47159. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  47160. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  47161. };
  47162. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  47163. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  47164. };
  47165. Animation.prototype.clone = function () {
  47166. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  47167. clone.enableBlending = this.enableBlending;
  47168. clone.blendingSpeed = this.blendingSpeed;
  47169. if (this._keys) {
  47170. clone.setKeys(this._keys);
  47171. }
  47172. if (this._ranges) {
  47173. clone._ranges = {};
  47174. for (var name in this._ranges) {
  47175. var range = this._ranges[name];
  47176. if (!range) {
  47177. continue;
  47178. }
  47179. clone._ranges[name] = range.clone();
  47180. }
  47181. }
  47182. return clone;
  47183. };
  47184. Animation.prototype.setKeys = function (values) {
  47185. this._keys = values.slice(0);
  47186. };
  47187. Animation.prototype.serialize = function () {
  47188. var serializationObject = {};
  47189. serializationObject.name = this.name;
  47190. serializationObject.property = this.targetProperty;
  47191. serializationObject.framePerSecond = this.framePerSecond;
  47192. serializationObject.dataType = this.dataType;
  47193. serializationObject.loopBehavior = this.loopMode;
  47194. serializationObject.enableBlending = this.enableBlending;
  47195. serializationObject.blendingSpeed = this.blendingSpeed;
  47196. var dataType = this.dataType;
  47197. serializationObject.keys = [];
  47198. var keys = this.getKeys();
  47199. for (var index = 0; index < keys.length; index++) {
  47200. var animationKey = keys[index];
  47201. var key = {};
  47202. key.frame = animationKey.frame;
  47203. switch (dataType) {
  47204. case Animation.ANIMATIONTYPE_FLOAT:
  47205. key.values = [animationKey.value];
  47206. break;
  47207. case Animation.ANIMATIONTYPE_QUATERNION:
  47208. case Animation.ANIMATIONTYPE_MATRIX:
  47209. case Animation.ANIMATIONTYPE_VECTOR3:
  47210. case Animation.ANIMATIONTYPE_COLOR3:
  47211. key.values = animationKey.value.asArray();
  47212. break;
  47213. }
  47214. serializationObject.keys.push(key);
  47215. }
  47216. serializationObject.ranges = [];
  47217. for (var name in this._ranges) {
  47218. var source = this._ranges[name];
  47219. if (!source) {
  47220. continue;
  47221. }
  47222. var range = {};
  47223. range.name = name;
  47224. range.from = source.from;
  47225. range.to = source.to;
  47226. serializationObject.ranges.push(range);
  47227. }
  47228. return serializationObject;
  47229. };
  47230. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  47231. get: function () {
  47232. return Animation._ANIMATIONTYPE_FLOAT;
  47233. },
  47234. enumerable: true,
  47235. configurable: true
  47236. });
  47237. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  47238. get: function () {
  47239. return Animation._ANIMATIONTYPE_VECTOR3;
  47240. },
  47241. enumerable: true,
  47242. configurable: true
  47243. });
  47244. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  47245. get: function () {
  47246. return Animation._ANIMATIONTYPE_VECTOR2;
  47247. },
  47248. enumerable: true,
  47249. configurable: true
  47250. });
  47251. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  47252. get: function () {
  47253. return Animation._ANIMATIONTYPE_SIZE;
  47254. },
  47255. enumerable: true,
  47256. configurable: true
  47257. });
  47258. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  47259. get: function () {
  47260. return Animation._ANIMATIONTYPE_QUATERNION;
  47261. },
  47262. enumerable: true,
  47263. configurable: true
  47264. });
  47265. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  47266. get: function () {
  47267. return Animation._ANIMATIONTYPE_MATRIX;
  47268. },
  47269. enumerable: true,
  47270. configurable: true
  47271. });
  47272. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  47273. get: function () {
  47274. return Animation._ANIMATIONTYPE_COLOR3;
  47275. },
  47276. enumerable: true,
  47277. configurable: true
  47278. });
  47279. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  47280. get: function () {
  47281. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  47282. },
  47283. enumerable: true,
  47284. configurable: true
  47285. });
  47286. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  47287. get: function () {
  47288. return Animation._ANIMATIONLOOPMODE_CYCLE;
  47289. },
  47290. enumerable: true,
  47291. configurable: true
  47292. });
  47293. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  47294. get: function () {
  47295. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  47296. },
  47297. enumerable: true,
  47298. configurable: true
  47299. });
  47300. Animation.Parse = function (parsedAnimation) {
  47301. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  47302. var dataType = parsedAnimation.dataType;
  47303. var keys = [];
  47304. var data;
  47305. var index;
  47306. if (parsedAnimation.enableBlending) {
  47307. animation.enableBlending = parsedAnimation.enableBlending;
  47308. }
  47309. if (parsedAnimation.blendingSpeed) {
  47310. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  47311. }
  47312. for (index = 0; index < parsedAnimation.keys.length; index++) {
  47313. var key = parsedAnimation.keys[index];
  47314. var inTangent;
  47315. var outTangent;
  47316. switch (dataType) {
  47317. case Animation.ANIMATIONTYPE_FLOAT:
  47318. data = key.values[0];
  47319. if (key.values.length >= 1) {
  47320. inTangent = key.values[1];
  47321. }
  47322. if (key.values.length >= 2) {
  47323. outTangent = key.values[2];
  47324. }
  47325. break;
  47326. case Animation.ANIMATIONTYPE_QUATERNION:
  47327. data = BABYLON.Quaternion.FromArray(key.values);
  47328. if (key.values.length >= 8) {
  47329. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  47330. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  47331. inTangent = _inTangent;
  47332. }
  47333. }
  47334. if (key.values.length >= 12) {
  47335. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  47336. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  47337. outTangent = _outTangent;
  47338. }
  47339. }
  47340. break;
  47341. case Animation.ANIMATIONTYPE_MATRIX:
  47342. data = BABYLON.Matrix.FromArray(key.values);
  47343. break;
  47344. case Animation.ANIMATIONTYPE_COLOR3:
  47345. data = BABYLON.Color3.FromArray(key.values);
  47346. break;
  47347. case Animation.ANIMATIONTYPE_VECTOR3:
  47348. default:
  47349. data = BABYLON.Vector3.FromArray(key.values);
  47350. break;
  47351. }
  47352. var keyData = {};
  47353. keyData.frame = key.frame;
  47354. keyData.value = data;
  47355. if (inTangent != undefined) {
  47356. keyData.inTangent = inTangent;
  47357. }
  47358. if (outTangent != undefined) {
  47359. keyData.outTangent = outTangent;
  47360. }
  47361. keys.push(keyData);
  47362. }
  47363. animation.setKeys(keys);
  47364. if (parsedAnimation.ranges) {
  47365. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  47366. data = parsedAnimation.ranges[index];
  47367. animation.createRange(data.name, data.from, data.to);
  47368. }
  47369. }
  47370. return animation;
  47371. };
  47372. Animation.AppendSerializedAnimations = function (source, destination) {
  47373. if (source.animations) {
  47374. destination.animations = [];
  47375. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  47376. var animation = source.animations[animationIndex];
  47377. destination.animations.push(animation.serialize());
  47378. }
  47379. }
  47380. };
  47381. Animation.AllowMatricesInterpolation = false;
  47382. // Statics
  47383. Animation._ANIMATIONTYPE_FLOAT = 0;
  47384. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  47385. Animation._ANIMATIONTYPE_QUATERNION = 2;
  47386. Animation._ANIMATIONTYPE_MATRIX = 3;
  47387. Animation._ANIMATIONTYPE_COLOR3 = 4;
  47388. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  47389. Animation._ANIMATIONTYPE_SIZE = 6;
  47390. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  47391. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  47392. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  47393. return Animation;
  47394. }());
  47395. BABYLON.Animation = Animation;
  47396. })(BABYLON || (BABYLON = {}));
  47397. //# sourceMappingURL=babylon.animation.js.map
  47398. "use strict";
  47399. var BABYLON;
  47400. (function (BABYLON) {
  47401. /**
  47402. * This class defines the direct association between an animation and a target
  47403. */
  47404. var TargetedAnimation = /** @class */ (function () {
  47405. function TargetedAnimation() {
  47406. }
  47407. return TargetedAnimation;
  47408. }());
  47409. BABYLON.TargetedAnimation = TargetedAnimation;
  47410. /**
  47411. * Use this class to create coordinated animations on multiple targets
  47412. */
  47413. var AnimationGroup = /** @class */ (function () {
  47414. function AnimationGroup(name, scene) {
  47415. if (scene === void 0) { scene = null; }
  47416. this.name = name;
  47417. this._targetedAnimations = new Array();
  47418. this._animatables = new Array();
  47419. this._from = Number.MAX_VALUE;
  47420. this._to = -Number.MAX_VALUE;
  47421. this._speedRatio = 1;
  47422. this.onAnimationEndObservable = new BABYLON.Observable();
  47423. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  47424. this._scene.animationGroups.push(this);
  47425. }
  47426. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  47427. /**
  47428. * Define if the animations are started
  47429. */
  47430. get: function () {
  47431. return this._isStarted;
  47432. },
  47433. enumerable: true,
  47434. configurable: true
  47435. });
  47436. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  47437. /**
  47438. * Gets or sets the speed ratio to use for all animations
  47439. */
  47440. get: function () {
  47441. return this._speedRatio;
  47442. },
  47443. /**
  47444. * Gets or sets the speed ratio to use for all animations
  47445. */
  47446. set: function (value) {
  47447. if (this._speedRatio === value) {
  47448. return;
  47449. }
  47450. this._speedRatio = value;
  47451. for (var index = 0; index < this._animatables.length; index++) {
  47452. var animatable = this._animatables[index];
  47453. animatable.speedRatio = this._speedRatio;
  47454. }
  47455. },
  47456. enumerable: true,
  47457. configurable: true
  47458. });
  47459. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  47460. /**
  47461. * Gets the targeted animations for this animation group
  47462. */
  47463. get: function () {
  47464. return this._targetedAnimations;
  47465. },
  47466. enumerable: true,
  47467. configurable: true
  47468. });
  47469. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  47470. /**
  47471. * returning the list of animatables controlled by this animation group.
  47472. */
  47473. get: function () {
  47474. return this._animatables;
  47475. },
  47476. enumerable: true,
  47477. configurable: true
  47478. });
  47479. /**
  47480. * Add an animation (with its target) in the group
  47481. * @param animation defines the animation we want to add
  47482. * @param target defines the target of the animation
  47483. * @returns the {BABYLON.TargetedAnimation} object
  47484. */
  47485. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  47486. var targetedAnimation = {
  47487. animation: animation,
  47488. target: target
  47489. };
  47490. var keys = animation.getKeys();
  47491. if (this._from > keys[0].frame) {
  47492. this._from = keys[0].frame;
  47493. }
  47494. if (this._to < keys[keys.length - 1].frame) {
  47495. this._to = keys[keys.length - 1].frame;
  47496. }
  47497. this._targetedAnimations.push(targetedAnimation);
  47498. return targetedAnimation;
  47499. };
  47500. /**
  47501. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  47502. * It can add constant keys at begin or end
  47503. * @param beginFrame defines the new begin frame for all animations. It can't be bigger than the smallest begin frame of all animations
  47504. * @param endFrame defines the new end frame for all animations. It can't be smaller than the largest end frame of all animations
  47505. */
  47506. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  47507. if (beginFrame === void 0) { beginFrame = -Number.MAX_VALUE; }
  47508. if (endFrame === void 0) { endFrame = Number.MAX_VALUE; }
  47509. beginFrame = Math.max(beginFrame, this._from);
  47510. endFrame = Math.min(endFrame, this._to);
  47511. for (var index = 0; index < this._targetedAnimations.length; index++) {
  47512. var targetedAnimation = this._targetedAnimations[index];
  47513. var keys = targetedAnimation.animation.getKeys();
  47514. var startKey = keys[0];
  47515. var endKey = keys[keys.length - 1];
  47516. if (startKey.frame > beginFrame) {
  47517. var newKey = {
  47518. frame: beginFrame,
  47519. value: startKey.value,
  47520. inTangent: startKey.inTangent,
  47521. outTangent: startKey.outTangent,
  47522. interpolation: startKey.interpolation
  47523. };
  47524. keys.splice(0, 0, newKey);
  47525. }
  47526. if (endKey.frame < endFrame) {
  47527. var newKey = {
  47528. frame: endFrame,
  47529. value: endKey.value,
  47530. inTangent: endKey.outTangent,
  47531. outTangent: endKey.outTangent,
  47532. interpolation: endKey.interpolation
  47533. };
  47534. keys.push(newKey);
  47535. }
  47536. }
  47537. return this;
  47538. };
  47539. /**
  47540. * Start all animations on given targets
  47541. * @param loop defines if animations must loop
  47542. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  47543. */
  47544. AnimationGroup.prototype.start = function (loop, speedRatio) {
  47545. var _this = this;
  47546. if (loop === void 0) { loop = false; }
  47547. if (speedRatio === void 0) { speedRatio = 1; }
  47548. if (this._isStarted || this._targetedAnimations.length === 0) {
  47549. return this;
  47550. }
  47551. var _loop_1 = function () {
  47552. var targetedAnimation = this_1._targetedAnimations[index];
  47553. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], this_1._from, this_1._to, loop, speedRatio, function () {
  47554. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  47555. }));
  47556. };
  47557. var this_1 = this;
  47558. for (var index = 0; index < this._targetedAnimations.length; index++) {
  47559. _loop_1();
  47560. }
  47561. this._speedRatio = speedRatio;
  47562. this._isStarted = true;
  47563. return this;
  47564. };
  47565. /**
  47566. * Pause all animations
  47567. */
  47568. AnimationGroup.prototype.pause = function () {
  47569. if (!this._isStarted) {
  47570. return this;
  47571. }
  47572. for (var index = 0; index < this._animatables.length; index++) {
  47573. var animatable = this._animatables[index];
  47574. animatable.pause();
  47575. }
  47576. return this;
  47577. };
  47578. /**
  47579. * Play all animations to initial state
  47580. * This function will start() the animations if they were not started or will restart() them if they were paused
  47581. * @param loop defines if animations must loop
  47582. */
  47583. AnimationGroup.prototype.play = function (loop) {
  47584. if (this.isStarted) {
  47585. if (loop !== undefined) {
  47586. for (var index = 0; index < this._animatables.length; index++) {
  47587. var animatable = this._animatables[index];
  47588. animatable.loopAnimation = loop;
  47589. }
  47590. }
  47591. this.restart();
  47592. }
  47593. else {
  47594. this.start(loop, this._speedRatio);
  47595. }
  47596. return this;
  47597. };
  47598. /**
  47599. * Reset all animations to initial state
  47600. */
  47601. AnimationGroup.prototype.reset = function () {
  47602. if (!this._isStarted) {
  47603. return this;
  47604. }
  47605. for (var index = 0; index < this._animatables.length; index++) {
  47606. var animatable = this._animatables[index];
  47607. animatable.reset();
  47608. }
  47609. return this;
  47610. };
  47611. /**
  47612. * Restart animations from key 0
  47613. */
  47614. AnimationGroup.prototype.restart = function () {
  47615. if (!this._isStarted) {
  47616. return this;
  47617. }
  47618. for (var index = 0; index < this._animatables.length; index++) {
  47619. var animatable = this._animatables[index];
  47620. animatable.restart();
  47621. }
  47622. return this;
  47623. };
  47624. /**
  47625. * Stop all animations
  47626. */
  47627. AnimationGroup.prototype.stop = function () {
  47628. if (!this._isStarted) {
  47629. return this;
  47630. }
  47631. for (var index = 0; index < this._animatables.length; index++) {
  47632. var animatable = this._animatables[index];
  47633. animatable.stop();
  47634. }
  47635. this._isStarted = false;
  47636. return this;
  47637. };
  47638. /**
  47639. * Goes to a specific frame in this animation group
  47640. *
  47641. * @param frame the frame number to go to
  47642. * @return the animationGroup
  47643. */
  47644. AnimationGroup.prototype.goToFrame = function (frame) {
  47645. if (!this._isStarted) {
  47646. return this;
  47647. }
  47648. for (var index = 0; index < this._animatables.length; index++) {
  47649. var animatable = this._animatables[index];
  47650. animatable.goToFrame(frame);
  47651. }
  47652. return this;
  47653. };
  47654. /**
  47655. * Dispose all associated resources
  47656. */
  47657. AnimationGroup.prototype.dispose = function () {
  47658. this._targetedAnimations = [];
  47659. this._animatables = [];
  47660. var index = this._scene.animationGroups.indexOf(this);
  47661. if (index > -1) {
  47662. this._scene.animationGroups.splice(index, 1);
  47663. }
  47664. };
  47665. return AnimationGroup;
  47666. }());
  47667. BABYLON.AnimationGroup = AnimationGroup;
  47668. })(BABYLON || (BABYLON = {}));
  47669. //# sourceMappingURL=babylon.animationGroup.js.map
  47670. "use strict";
  47671. var BABYLON;
  47672. (function (BABYLON) {
  47673. var RuntimeAnimation = /** @class */ (function () {
  47674. /**
  47675. * Create a new RuntimeAnimation object
  47676. * @param target defines the target of the animation
  47677. * @param animation defines the source {BABYLON.Animation} object
  47678. * @param scene defines the hosting scene
  47679. */
  47680. function RuntimeAnimation(target, animation, scene) {
  47681. this._offsetsCache = {};
  47682. this._highLimitsCache = {};
  47683. this._stopped = false;
  47684. this._blendingFactor = 0;
  47685. this._weight = 1.0;
  47686. this._ratioOffset = 0;
  47687. this._animation = animation;
  47688. this._target = target;
  47689. this._scene = scene;
  47690. animation._runtimeAnimations.push(this);
  47691. }
  47692. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  47693. /**
  47694. * Gets the weight of the runtime animation
  47695. */
  47696. get: function () {
  47697. return this._weight;
  47698. },
  47699. enumerable: true,
  47700. configurable: true
  47701. });
  47702. Object.defineProperty(RuntimeAnimation.prototype, "originalValue", {
  47703. /**
  47704. * Gets the original value of the runtime animation
  47705. */
  47706. get: function () {
  47707. return this._originalValue;
  47708. },
  47709. enumerable: true,
  47710. configurable: true
  47711. });
  47712. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  47713. /**
  47714. * Gets the current value of the runtime animation
  47715. */
  47716. get: function () {
  47717. return this._currentValue;
  47718. },
  47719. enumerable: true,
  47720. configurable: true
  47721. });
  47722. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  47723. /**
  47724. * Gets the path where to store the animated value in the target
  47725. */
  47726. get: function () {
  47727. return this._targetPath;
  47728. },
  47729. enumerable: true,
  47730. configurable: true
  47731. });
  47732. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  47733. /**
  47734. * Gets the actual target of the runtime animation
  47735. */
  47736. get: function () {
  47737. return this._activeTarget;
  47738. },
  47739. enumerable: true,
  47740. configurable: true
  47741. });
  47742. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  47743. get: function () {
  47744. return this._animation;
  47745. },
  47746. enumerable: true,
  47747. configurable: true
  47748. });
  47749. RuntimeAnimation.prototype.reset = function () {
  47750. this._offsetsCache = {};
  47751. this._highLimitsCache = {};
  47752. this.currentFrame = 0;
  47753. this._blendingFactor = 0;
  47754. this._originalValue = null;
  47755. };
  47756. RuntimeAnimation.prototype.isStopped = function () {
  47757. return this._stopped;
  47758. };
  47759. RuntimeAnimation.prototype.dispose = function () {
  47760. var index = this._animation.runtimeAnimations.indexOf(this);
  47761. if (index > -1) {
  47762. this._animation.runtimeAnimations.splice(index, 1);
  47763. }
  47764. };
  47765. RuntimeAnimation.prototype._getKeyValue = function (value) {
  47766. if (typeof value === "function") {
  47767. return value();
  47768. }
  47769. return value;
  47770. };
  47771. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  47772. if (loopMode === BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  47773. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  47774. }
  47775. this.currentFrame = currentFrame;
  47776. var keys = this._animation.getKeys();
  47777. // Try to get a hash to find the right key
  47778. 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));
  47779. if (keys[startKeyIndex].frame >= currentFrame) {
  47780. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  47781. startKeyIndex--;
  47782. }
  47783. }
  47784. for (var key = startKeyIndex; key < keys.length; key++) {
  47785. var endKey = keys[key + 1];
  47786. if (endKey.frame >= currentFrame) {
  47787. var startKey = keys[key];
  47788. var startValue = this._getKeyValue(startKey.value);
  47789. if (startKey.interpolation === BABYLON.AnimationKeyInterpolation.STEP) {
  47790. return startValue;
  47791. }
  47792. var endValue = this._getKeyValue(endKey.value);
  47793. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  47794. var frameDelta = endKey.frame - startKey.frame;
  47795. // gradient : percent of currentFrame between the frame inf and the frame sup
  47796. var gradient = (currentFrame - startKey.frame) / frameDelta;
  47797. // check for easingFunction and correction of gradient
  47798. var easingFunction = this._animation.getEasingFunction();
  47799. if (easingFunction != null) {
  47800. gradient = easingFunction.ease(gradient);
  47801. }
  47802. switch (this._animation.dataType) {
  47803. // Float
  47804. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  47805. var floatValue = useTangent ? this._animation.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this._animation.floatInterpolateFunction(startValue, endValue, gradient);
  47806. switch (loopMode) {
  47807. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47808. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47809. return floatValue;
  47810. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47811. return offsetValue * repeatCount + floatValue;
  47812. }
  47813. break;
  47814. // Quaternion
  47815. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  47816. var quatValue = useTangent ? this._animation.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.quaternionInterpolateFunction(startValue, endValue, gradient);
  47817. switch (loopMode) {
  47818. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47819. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47820. return quatValue;
  47821. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47822. return quatValue.add(offsetValue.scale(repeatCount));
  47823. }
  47824. return quatValue;
  47825. // Vector3
  47826. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  47827. var vec3Value = useTangent ? this._animation.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector3InterpolateFunction(startValue, endValue, gradient);
  47828. switch (loopMode) {
  47829. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47830. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47831. return vec3Value;
  47832. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47833. return vec3Value.add(offsetValue.scale(repeatCount));
  47834. }
  47835. // Vector2
  47836. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  47837. var vec2Value = useTangent ? this._animation.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this._animation.vector2InterpolateFunction(startValue, endValue, gradient);
  47838. switch (loopMode) {
  47839. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47840. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47841. return vec2Value;
  47842. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47843. return vec2Value.add(offsetValue.scale(repeatCount));
  47844. }
  47845. // Size
  47846. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  47847. switch (loopMode) {
  47848. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47849. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47850. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient);
  47851. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47852. return this._animation.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47853. }
  47854. // Color3
  47855. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  47856. switch (loopMode) {
  47857. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47858. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47859. return this._animation.color3InterpolateFunction(startValue, endValue, gradient);
  47860. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47861. return this._animation.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  47862. }
  47863. // Matrix
  47864. case BABYLON.Animation.ANIMATIONTYPE_MATRIX:
  47865. switch (loopMode) {
  47866. case BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE:
  47867. case BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT:
  47868. if (BABYLON.Animation.AllowMatricesInterpolation) {
  47869. return this._animation.matrixInterpolateFunction(startValue, endValue, gradient);
  47870. }
  47871. case BABYLON.Animation.ANIMATIONLOOPMODE_RELATIVE:
  47872. return startValue;
  47873. }
  47874. default:
  47875. break;
  47876. }
  47877. break;
  47878. }
  47879. }
  47880. return this._getKeyValue(keys[keys.length - 1].value);
  47881. };
  47882. /**
  47883. * Affect the interpolated value to the target
  47884. * @param currentValue defines the value computed by the animation
  47885. * @param weight defines the weight to apply to this value
  47886. */
  47887. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  47888. if (weight === void 0) { weight = 1.0; }
  47889. // Set value
  47890. var path;
  47891. var destination;
  47892. var targetPropertyPath = this._animation.targetPropertyPath;
  47893. if (targetPropertyPath.length > 1) {
  47894. var property = this._target[targetPropertyPath[0]];
  47895. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  47896. property = property[targetPropertyPath[index]];
  47897. }
  47898. path = [targetPropertyPath.length - 1];
  47899. destination = property;
  47900. }
  47901. else {
  47902. path = targetPropertyPath[0];
  47903. destination = this._target;
  47904. }
  47905. this._targetPath = path;
  47906. this._activeTarget = destination;
  47907. this._weight = weight;
  47908. // Blending
  47909. var enableBlending = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  47910. var blendingSpeed = this._target && this._target.animationPropertiesOverride ? this._target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  47911. if (enableBlending && this._blendingFactor <= 1.0 || weight !== -1.0) {
  47912. if (!this._originalValue) {
  47913. var originalValue = void 0;
  47914. if (destination.getRestPose) {
  47915. originalValue = destination.getRestPose();
  47916. }
  47917. else {
  47918. originalValue = destination[path];
  47919. }
  47920. if (originalValue.clone) {
  47921. this._originalValue = originalValue.clone();
  47922. }
  47923. else {
  47924. this._originalValue = originalValue;
  47925. }
  47926. }
  47927. }
  47928. if (enableBlending && this._blendingFactor <= 1.0) {
  47929. if (this._originalValue.prototype) {
  47930. if (this._originalValue.prototype.Lerp) {
  47931. this._currentValue = this._originalValue.construtor.prototype.Lerp(currentValue, this._originalValue, this._blendingFactor);
  47932. }
  47933. else {
  47934. this._currentValue = currentValue;
  47935. }
  47936. }
  47937. else if (this._originalValue.m) {
  47938. this._currentValue = BABYLON.Matrix.Lerp(this._originalValue, currentValue, this._blendingFactor);
  47939. }
  47940. else {
  47941. this._currentValue = this._originalValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  47942. }
  47943. this._blendingFactor += blendingSpeed;
  47944. destination[path] = this._currentValue;
  47945. }
  47946. else {
  47947. this._currentValue = currentValue;
  47948. if (weight !== -1.0) {
  47949. this._scene._registerTargetForLateAnimationBinding(this);
  47950. }
  47951. else {
  47952. destination[path] = this._currentValue;
  47953. }
  47954. }
  47955. if (this._target.markAsDirty) {
  47956. this._target.markAsDirty(this._animation.targetProperty);
  47957. }
  47958. };
  47959. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  47960. if (this._target && this._target.animationPropertiesOverride) {
  47961. return this._target.animationPropertiesOverride.loopMode;
  47962. }
  47963. return this._animation.loopMode;
  47964. };
  47965. /**
  47966. * Move the current animation to a given frame
  47967. * @param frame defines the frame to move to
  47968. */
  47969. RuntimeAnimation.prototype.goToFrame = function (frame) {
  47970. var keys = this._animation.getKeys();
  47971. if (frame < keys[0].frame) {
  47972. frame = keys[0].frame;
  47973. }
  47974. else if (frame > keys[keys.length - 1].frame) {
  47975. frame = keys[keys.length - 1].frame;
  47976. }
  47977. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  47978. this.setValue(currentValue, -1);
  47979. };
  47980. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  47981. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  47982. this._ratioOffset = this._previousRatio - newRatio;
  47983. };
  47984. /**
  47985. * Execute the current animation
  47986. * @param delay defines the delay to add to the current frame
  47987. * @param from defines the lower bound of the animation range
  47988. * @param to defines the upper bound of the animation range
  47989. * @param loop defines if the current animation must loop
  47990. * @param speedRatio defines the current speed ratio
  47991. * @param weight defines the weight of the animation (default is -1 so no weight)
  47992. * @returns a boolean indicating if the animation has ended
  47993. */
  47994. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  47995. if (weight === void 0) { weight = -1.0; }
  47996. var targetPropertyPath = this._animation.targetPropertyPath;
  47997. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  47998. this._stopped = true;
  47999. return false;
  48000. }
  48001. var returnValue = true;
  48002. var keys = this._animation.getKeys();
  48003. // Adding a start key at frame 0 if missing
  48004. if (keys[0].frame !== 0) {
  48005. var newKey = { frame: 0, value: keys[0].value };
  48006. keys.splice(0, 0, newKey);
  48007. }
  48008. // Check limits
  48009. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  48010. from = keys[0].frame;
  48011. }
  48012. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  48013. to = keys[keys.length - 1].frame;
  48014. }
  48015. //to and from cannot be the same key
  48016. if (from === to) {
  48017. if (from > keys[0].frame) {
  48018. from--;
  48019. }
  48020. else if (to < keys[keys.length - 1].frame) {
  48021. to++;
  48022. }
  48023. }
  48024. // Compute ratio
  48025. var range = to - from;
  48026. var offsetValue;
  48027. // ratio represents the frame delta between from and to
  48028. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  48029. var highLimitValue = 0;
  48030. this._previousDelay = delay;
  48031. this._previousRatio = ratio;
  48032. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  48033. returnValue = false;
  48034. highLimitValue = this._getKeyValue(keys[keys.length - 1].value);
  48035. }
  48036. else {
  48037. // Get max value if required
  48038. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  48039. var keyOffset = to.toString() + from.toString();
  48040. if (!this._offsetsCache[keyOffset]) {
  48041. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  48042. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  48043. switch (this._animation.dataType) {
  48044. // Float
  48045. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  48046. this._offsetsCache[keyOffset] = toValue - fromValue;
  48047. break;
  48048. // Quaternion
  48049. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  48050. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48051. break;
  48052. // Vector3
  48053. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  48054. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48055. // Vector2
  48056. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  48057. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48058. // Size
  48059. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  48060. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48061. // Color3
  48062. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  48063. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  48064. default:
  48065. break;
  48066. }
  48067. this._highLimitsCache[keyOffset] = toValue;
  48068. }
  48069. highLimitValue = this._highLimitsCache[keyOffset];
  48070. offsetValue = this._offsetsCache[keyOffset];
  48071. }
  48072. }
  48073. if (offsetValue === undefined) {
  48074. switch (this._animation.dataType) {
  48075. // Float
  48076. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  48077. offsetValue = 0;
  48078. break;
  48079. // Quaternion
  48080. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  48081. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  48082. break;
  48083. // Vector3
  48084. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  48085. offsetValue = BABYLON.Vector3.Zero();
  48086. break;
  48087. // Vector2
  48088. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  48089. offsetValue = BABYLON.Vector2.Zero();
  48090. break;
  48091. // Size
  48092. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  48093. offsetValue = BABYLON.Size.Zero();
  48094. break;
  48095. // Color3
  48096. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  48097. offsetValue = BABYLON.Color3.Black();
  48098. }
  48099. }
  48100. // Compute value
  48101. var repeatCount = (ratio / range) >> 0;
  48102. var currentFrame = returnValue ? from + ratio % range : to;
  48103. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  48104. // Set value
  48105. this.setValue(currentValue, weight);
  48106. // Check events
  48107. var events = this._animation.getEvents();
  48108. for (var index = 0; index < events.length; index++) {
  48109. // Make sure current frame has passed event frame and that event frame is within the current range
  48110. // Also, handle both forward and reverse animations
  48111. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  48112. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  48113. var event = events[index];
  48114. if (!event.isDone) {
  48115. // If event should be done only once, remove it.
  48116. if (event.onlyOnce) {
  48117. events.splice(index, 1);
  48118. index--;
  48119. }
  48120. event.isDone = true;
  48121. event.action();
  48122. } // Don't do anything if the event has already be done.
  48123. }
  48124. else if (events[index].isDone && !events[index].onlyOnce) {
  48125. // reset event, the animation is looping
  48126. events[index].isDone = false;
  48127. }
  48128. }
  48129. if (!returnValue) {
  48130. this._stopped = true;
  48131. }
  48132. return returnValue;
  48133. };
  48134. return RuntimeAnimation;
  48135. }());
  48136. BABYLON.RuntimeAnimation = RuntimeAnimation;
  48137. })(BABYLON || (BABYLON = {}));
  48138. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  48139. "use strict";
  48140. var BABYLON;
  48141. (function (BABYLON) {
  48142. var Animatable = /** @class */ (function () {
  48143. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  48144. if (fromFrame === void 0) { fromFrame = 0; }
  48145. if (toFrame === void 0) { toFrame = 100; }
  48146. if (loopAnimation === void 0) { loopAnimation = false; }
  48147. if (speedRatio === void 0) { speedRatio = 1.0; }
  48148. this.target = target;
  48149. this.fromFrame = fromFrame;
  48150. this.toFrame = toFrame;
  48151. this.loopAnimation = loopAnimation;
  48152. this.onAnimationEnd = onAnimationEnd;
  48153. this._localDelayOffset = null;
  48154. this._pausedDelay = null;
  48155. this._runtimeAnimations = new Array();
  48156. this._paused = false;
  48157. this._speedRatio = 1;
  48158. this._weight = -1.0;
  48159. this.animationStarted = false;
  48160. if (animations) {
  48161. this.appendAnimations(target, animations);
  48162. }
  48163. this._speedRatio = speedRatio;
  48164. this._scene = scene;
  48165. scene._activeAnimatables.push(this);
  48166. }
  48167. Object.defineProperty(Animatable.prototype, "weight", {
  48168. /**
  48169. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  48170. */
  48171. get: function () {
  48172. return this._weight;
  48173. },
  48174. set: function (value) {
  48175. if (value === -1) {
  48176. this._weight = -1;
  48177. return;
  48178. }
  48179. // Else weight must be in [0, 1] range
  48180. this._weight = Math.min(Math.max(value, 0), 1.0);
  48181. },
  48182. enumerable: true,
  48183. configurable: true
  48184. });
  48185. Object.defineProperty(Animatable.prototype, "speedRatio", {
  48186. /**
  48187. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  48188. */
  48189. get: function () {
  48190. return this._speedRatio;
  48191. },
  48192. set: function (value) {
  48193. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  48194. var animation = this._runtimeAnimations[index];
  48195. animation._prepareForSpeedRatioChange(value);
  48196. }
  48197. this._speedRatio = value;
  48198. },
  48199. enumerable: true,
  48200. configurable: true
  48201. });
  48202. // Methods
  48203. Animatable.prototype.getAnimations = function () {
  48204. return this._runtimeAnimations;
  48205. };
  48206. Animatable.prototype.appendAnimations = function (target, animations) {
  48207. for (var index = 0; index < animations.length; index++) {
  48208. var animation = animations[index];
  48209. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene));
  48210. }
  48211. };
  48212. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  48213. var runtimeAnimations = this._runtimeAnimations;
  48214. for (var index = 0; index < runtimeAnimations.length; index++) {
  48215. if (runtimeAnimations[index].animation.targetProperty === property) {
  48216. return runtimeAnimations[index].animation;
  48217. }
  48218. }
  48219. return null;
  48220. };
  48221. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  48222. var runtimeAnimations = this._runtimeAnimations;
  48223. for (var index = 0; index < runtimeAnimations.length; index++) {
  48224. if (runtimeAnimations[index].animation.targetProperty === property) {
  48225. return runtimeAnimations[index];
  48226. }
  48227. }
  48228. return null;
  48229. };
  48230. Animatable.prototype.reset = function () {
  48231. var runtimeAnimations = this._runtimeAnimations;
  48232. for (var index = 0; index < runtimeAnimations.length; index++) {
  48233. runtimeAnimations[index].reset();
  48234. }
  48235. // Reset to original value
  48236. for (index = 0; index < runtimeAnimations.length; index++) {
  48237. var animation = runtimeAnimations[index];
  48238. animation.animate(0, this.fromFrame, this.toFrame, false, this._speedRatio);
  48239. }
  48240. this._localDelayOffset = null;
  48241. this._pausedDelay = null;
  48242. };
  48243. Animatable.prototype.enableBlending = function (blendingSpeed) {
  48244. var runtimeAnimations = this._runtimeAnimations;
  48245. for (var index = 0; index < runtimeAnimations.length; index++) {
  48246. runtimeAnimations[index].animation.enableBlending = true;
  48247. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  48248. }
  48249. };
  48250. Animatable.prototype.disableBlending = function () {
  48251. var runtimeAnimations = this._runtimeAnimations;
  48252. for (var index = 0; index < runtimeAnimations.length; index++) {
  48253. runtimeAnimations[index].animation.enableBlending = false;
  48254. }
  48255. };
  48256. Animatable.prototype.goToFrame = function (frame) {
  48257. var runtimeAnimations = this._runtimeAnimations;
  48258. if (runtimeAnimations[0]) {
  48259. var fps = runtimeAnimations[0].animation.framePerSecond;
  48260. var currentFrame = runtimeAnimations[0].currentFrame;
  48261. var adjustTime = frame - currentFrame;
  48262. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  48263. if (this._localDelayOffset === null) {
  48264. this._localDelayOffset = 0;
  48265. }
  48266. this._localDelayOffset -= delay;
  48267. }
  48268. for (var index = 0; index < runtimeAnimations.length; index++) {
  48269. runtimeAnimations[index].goToFrame(frame);
  48270. }
  48271. };
  48272. Animatable.prototype.pause = function () {
  48273. if (this._paused) {
  48274. return;
  48275. }
  48276. this._paused = true;
  48277. };
  48278. Animatable.prototype.restart = function () {
  48279. this._paused = false;
  48280. };
  48281. Animatable.prototype.stop = function (animationName) {
  48282. if (animationName) {
  48283. var idx = this._scene._activeAnimatables.indexOf(this);
  48284. if (idx > -1) {
  48285. var runtimeAnimations = this._runtimeAnimations;
  48286. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  48287. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  48288. continue;
  48289. }
  48290. runtimeAnimations[index].dispose();
  48291. runtimeAnimations.splice(index, 1);
  48292. }
  48293. if (runtimeAnimations.length == 0) {
  48294. this._scene._activeAnimatables.splice(idx, 1);
  48295. if (this.onAnimationEnd) {
  48296. this.onAnimationEnd();
  48297. }
  48298. }
  48299. }
  48300. }
  48301. else {
  48302. var index = this._scene._activeAnimatables.indexOf(this);
  48303. if (index > -1) {
  48304. this._scene._activeAnimatables.splice(index, 1);
  48305. var runtimeAnimations = this._runtimeAnimations;
  48306. for (var index = 0; index < runtimeAnimations.length; index++) {
  48307. runtimeAnimations[index].dispose();
  48308. }
  48309. if (this.onAnimationEnd) {
  48310. this.onAnimationEnd();
  48311. }
  48312. }
  48313. }
  48314. };
  48315. Animatable.prototype._animate = function (delay) {
  48316. if (this._paused) {
  48317. this.animationStarted = false;
  48318. if (this._pausedDelay === null) {
  48319. this._pausedDelay = delay;
  48320. }
  48321. return true;
  48322. }
  48323. if (this._localDelayOffset === null) {
  48324. this._localDelayOffset = delay;
  48325. this._pausedDelay = null;
  48326. }
  48327. else if (this._pausedDelay !== null) {
  48328. this._localDelayOffset += delay - this._pausedDelay;
  48329. this._pausedDelay = null;
  48330. }
  48331. // Animating
  48332. var running = false;
  48333. var runtimeAnimations = this._runtimeAnimations;
  48334. var index;
  48335. for (index = 0; index < runtimeAnimations.length; index++) {
  48336. var animation = runtimeAnimations[index];
  48337. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  48338. running = running || isRunning;
  48339. }
  48340. this.animationStarted = running;
  48341. if (!running) {
  48342. // Remove from active animatables
  48343. index = this._scene._activeAnimatables.indexOf(this);
  48344. this._scene._activeAnimatables.splice(index, 1);
  48345. // Dispose all runtime animations
  48346. for (index = 0; index < runtimeAnimations.length; index++) {
  48347. runtimeAnimations[index].dispose();
  48348. }
  48349. }
  48350. if (!running && this.onAnimationEnd) {
  48351. this.onAnimationEnd();
  48352. this.onAnimationEnd = null;
  48353. }
  48354. return running;
  48355. };
  48356. return Animatable;
  48357. }());
  48358. BABYLON.Animatable = Animatable;
  48359. })(BABYLON || (BABYLON = {}));
  48360. //# sourceMappingURL=babylon.animatable.js.map
  48361. "use strict";
  48362. var BABYLON;
  48363. (function (BABYLON) {
  48364. var EasingFunction = /** @class */ (function () {
  48365. function EasingFunction() {
  48366. // Properties
  48367. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  48368. }
  48369. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  48370. get: function () {
  48371. return EasingFunction._EASINGMODE_EASEIN;
  48372. },
  48373. enumerable: true,
  48374. configurable: true
  48375. });
  48376. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  48377. get: function () {
  48378. return EasingFunction._EASINGMODE_EASEOUT;
  48379. },
  48380. enumerable: true,
  48381. configurable: true
  48382. });
  48383. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  48384. get: function () {
  48385. return EasingFunction._EASINGMODE_EASEINOUT;
  48386. },
  48387. enumerable: true,
  48388. configurable: true
  48389. });
  48390. EasingFunction.prototype.setEasingMode = function (easingMode) {
  48391. var n = Math.min(Math.max(easingMode, 0), 2);
  48392. this._easingMode = n;
  48393. };
  48394. EasingFunction.prototype.getEasingMode = function () {
  48395. return this._easingMode;
  48396. };
  48397. EasingFunction.prototype.easeInCore = function (gradient) {
  48398. throw new Error('You must implement this method');
  48399. };
  48400. EasingFunction.prototype.ease = function (gradient) {
  48401. switch (this._easingMode) {
  48402. case EasingFunction.EASINGMODE_EASEIN:
  48403. return this.easeInCore(gradient);
  48404. case EasingFunction.EASINGMODE_EASEOUT:
  48405. return (1 - this.easeInCore(1 - gradient));
  48406. }
  48407. if (gradient >= 0.5) {
  48408. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  48409. }
  48410. return (this.easeInCore(gradient * 2) * 0.5);
  48411. };
  48412. //Statics
  48413. EasingFunction._EASINGMODE_EASEIN = 0;
  48414. EasingFunction._EASINGMODE_EASEOUT = 1;
  48415. EasingFunction._EASINGMODE_EASEINOUT = 2;
  48416. return EasingFunction;
  48417. }());
  48418. BABYLON.EasingFunction = EasingFunction;
  48419. var CircleEase = /** @class */ (function (_super) {
  48420. __extends(CircleEase, _super);
  48421. function CircleEase() {
  48422. return _super !== null && _super.apply(this, arguments) || this;
  48423. }
  48424. CircleEase.prototype.easeInCore = function (gradient) {
  48425. gradient = Math.max(0, Math.min(1, gradient));
  48426. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  48427. };
  48428. return CircleEase;
  48429. }(EasingFunction));
  48430. BABYLON.CircleEase = CircleEase;
  48431. var BackEase = /** @class */ (function (_super) {
  48432. __extends(BackEase, _super);
  48433. function BackEase(amplitude) {
  48434. if (amplitude === void 0) { amplitude = 1; }
  48435. var _this = _super.call(this) || this;
  48436. _this.amplitude = amplitude;
  48437. return _this;
  48438. }
  48439. BackEase.prototype.easeInCore = function (gradient) {
  48440. var num = Math.max(0, this.amplitude);
  48441. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  48442. };
  48443. return BackEase;
  48444. }(EasingFunction));
  48445. BABYLON.BackEase = BackEase;
  48446. var BounceEase = /** @class */ (function (_super) {
  48447. __extends(BounceEase, _super);
  48448. function BounceEase(bounces, bounciness) {
  48449. if (bounces === void 0) { bounces = 3; }
  48450. if (bounciness === void 0) { bounciness = 2; }
  48451. var _this = _super.call(this) || this;
  48452. _this.bounces = bounces;
  48453. _this.bounciness = bounciness;
  48454. return _this;
  48455. }
  48456. BounceEase.prototype.easeInCore = function (gradient) {
  48457. var y = Math.max(0.0, this.bounces);
  48458. var bounciness = this.bounciness;
  48459. if (bounciness <= 1.0) {
  48460. bounciness = 1.001;
  48461. }
  48462. var num9 = Math.pow(bounciness, y);
  48463. var num5 = 1.0 - bounciness;
  48464. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  48465. var num15 = gradient * num4;
  48466. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  48467. var num3 = Math.floor(num65);
  48468. var num13 = num3 + 1.0;
  48469. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  48470. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  48471. var num7 = (num8 + num12) * 0.5;
  48472. var num6 = gradient - num7;
  48473. var num2 = num7 - num8;
  48474. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  48475. };
  48476. return BounceEase;
  48477. }(EasingFunction));
  48478. BABYLON.BounceEase = BounceEase;
  48479. var CubicEase = /** @class */ (function (_super) {
  48480. __extends(CubicEase, _super);
  48481. function CubicEase() {
  48482. return _super !== null && _super.apply(this, arguments) || this;
  48483. }
  48484. CubicEase.prototype.easeInCore = function (gradient) {
  48485. return (gradient * gradient * gradient);
  48486. };
  48487. return CubicEase;
  48488. }(EasingFunction));
  48489. BABYLON.CubicEase = CubicEase;
  48490. var ElasticEase = /** @class */ (function (_super) {
  48491. __extends(ElasticEase, _super);
  48492. function ElasticEase(oscillations, springiness) {
  48493. if (oscillations === void 0) { oscillations = 3; }
  48494. if (springiness === void 0) { springiness = 3; }
  48495. var _this = _super.call(this) || this;
  48496. _this.oscillations = oscillations;
  48497. _this.springiness = springiness;
  48498. return _this;
  48499. }
  48500. ElasticEase.prototype.easeInCore = function (gradient) {
  48501. var num2;
  48502. var num3 = Math.max(0.0, this.oscillations);
  48503. var num = Math.max(0.0, this.springiness);
  48504. if (num == 0) {
  48505. num2 = gradient;
  48506. }
  48507. else {
  48508. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  48509. }
  48510. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  48511. };
  48512. return ElasticEase;
  48513. }(EasingFunction));
  48514. BABYLON.ElasticEase = ElasticEase;
  48515. var ExponentialEase = /** @class */ (function (_super) {
  48516. __extends(ExponentialEase, _super);
  48517. function ExponentialEase(exponent) {
  48518. if (exponent === void 0) { exponent = 2; }
  48519. var _this = _super.call(this) || this;
  48520. _this.exponent = exponent;
  48521. return _this;
  48522. }
  48523. ExponentialEase.prototype.easeInCore = function (gradient) {
  48524. if (this.exponent <= 0) {
  48525. return gradient;
  48526. }
  48527. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  48528. };
  48529. return ExponentialEase;
  48530. }(EasingFunction));
  48531. BABYLON.ExponentialEase = ExponentialEase;
  48532. var PowerEase = /** @class */ (function (_super) {
  48533. __extends(PowerEase, _super);
  48534. function PowerEase(power) {
  48535. if (power === void 0) { power = 2; }
  48536. var _this = _super.call(this) || this;
  48537. _this.power = power;
  48538. return _this;
  48539. }
  48540. PowerEase.prototype.easeInCore = function (gradient) {
  48541. var y = Math.max(0.0, this.power);
  48542. return Math.pow(gradient, y);
  48543. };
  48544. return PowerEase;
  48545. }(EasingFunction));
  48546. BABYLON.PowerEase = PowerEase;
  48547. var QuadraticEase = /** @class */ (function (_super) {
  48548. __extends(QuadraticEase, _super);
  48549. function QuadraticEase() {
  48550. return _super !== null && _super.apply(this, arguments) || this;
  48551. }
  48552. QuadraticEase.prototype.easeInCore = function (gradient) {
  48553. return (gradient * gradient);
  48554. };
  48555. return QuadraticEase;
  48556. }(EasingFunction));
  48557. BABYLON.QuadraticEase = QuadraticEase;
  48558. var QuarticEase = /** @class */ (function (_super) {
  48559. __extends(QuarticEase, _super);
  48560. function QuarticEase() {
  48561. return _super !== null && _super.apply(this, arguments) || this;
  48562. }
  48563. QuarticEase.prototype.easeInCore = function (gradient) {
  48564. return (gradient * gradient * gradient * gradient);
  48565. };
  48566. return QuarticEase;
  48567. }(EasingFunction));
  48568. BABYLON.QuarticEase = QuarticEase;
  48569. var QuinticEase = /** @class */ (function (_super) {
  48570. __extends(QuinticEase, _super);
  48571. function QuinticEase() {
  48572. return _super !== null && _super.apply(this, arguments) || this;
  48573. }
  48574. QuinticEase.prototype.easeInCore = function (gradient) {
  48575. return (gradient * gradient * gradient * gradient * gradient);
  48576. };
  48577. return QuinticEase;
  48578. }(EasingFunction));
  48579. BABYLON.QuinticEase = QuinticEase;
  48580. var SineEase = /** @class */ (function (_super) {
  48581. __extends(SineEase, _super);
  48582. function SineEase() {
  48583. return _super !== null && _super.apply(this, arguments) || this;
  48584. }
  48585. SineEase.prototype.easeInCore = function (gradient) {
  48586. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  48587. };
  48588. return SineEase;
  48589. }(EasingFunction));
  48590. BABYLON.SineEase = SineEase;
  48591. var BezierCurveEase = /** @class */ (function (_super) {
  48592. __extends(BezierCurveEase, _super);
  48593. function BezierCurveEase(x1, y1, x2, y2) {
  48594. if (x1 === void 0) { x1 = 0; }
  48595. if (y1 === void 0) { y1 = 0; }
  48596. if (x2 === void 0) { x2 = 1; }
  48597. if (y2 === void 0) { y2 = 1; }
  48598. var _this = _super.call(this) || this;
  48599. _this.x1 = x1;
  48600. _this.y1 = y1;
  48601. _this.x2 = x2;
  48602. _this.y2 = y2;
  48603. return _this;
  48604. }
  48605. BezierCurveEase.prototype.easeInCore = function (gradient) {
  48606. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  48607. };
  48608. return BezierCurveEase;
  48609. }(EasingFunction));
  48610. BABYLON.BezierCurveEase = BezierCurveEase;
  48611. })(BABYLON || (BABYLON = {}));
  48612. //# sourceMappingURL=babylon.easing.js.map
  48613. "use strict";
  48614. var BABYLON;
  48615. (function (BABYLON) {
  48616. var Condition = /** @class */ (function () {
  48617. function Condition(actionManager) {
  48618. this._actionManager = actionManager;
  48619. }
  48620. Condition.prototype.isValid = function () {
  48621. return true;
  48622. };
  48623. Condition.prototype._getProperty = function (propertyPath) {
  48624. return this._actionManager._getProperty(propertyPath);
  48625. };
  48626. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  48627. return this._actionManager._getEffectiveTarget(target, propertyPath);
  48628. };
  48629. Condition.prototype.serialize = function () {
  48630. };
  48631. Condition.prototype._serialize = function (serializedCondition) {
  48632. return {
  48633. type: 2,
  48634. children: [],
  48635. name: serializedCondition.name,
  48636. properties: serializedCondition.properties
  48637. };
  48638. };
  48639. return Condition;
  48640. }());
  48641. BABYLON.Condition = Condition;
  48642. var ValueCondition = /** @class */ (function (_super) {
  48643. __extends(ValueCondition, _super);
  48644. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  48645. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  48646. var _this = _super.call(this, actionManager) || this;
  48647. _this.propertyPath = propertyPath;
  48648. _this.value = value;
  48649. _this.operator = operator;
  48650. _this._target = target;
  48651. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  48652. _this._property = _this._getProperty(_this.propertyPath);
  48653. return _this;
  48654. }
  48655. Object.defineProperty(ValueCondition, "IsEqual", {
  48656. get: function () {
  48657. return ValueCondition._IsEqual;
  48658. },
  48659. enumerable: true,
  48660. configurable: true
  48661. });
  48662. Object.defineProperty(ValueCondition, "IsDifferent", {
  48663. get: function () {
  48664. return ValueCondition._IsDifferent;
  48665. },
  48666. enumerable: true,
  48667. configurable: true
  48668. });
  48669. Object.defineProperty(ValueCondition, "IsGreater", {
  48670. get: function () {
  48671. return ValueCondition._IsGreater;
  48672. },
  48673. enumerable: true,
  48674. configurable: true
  48675. });
  48676. Object.defineProperty(ValueCondition, "IsLesser", {
  48677. get: function () {
  48678. return ValueCondition._IsLesser;
  48679. },
  48680. enumerable: true,
  48681. configurable: true
  48682. });
  48683. // Methods
  48684. ValueCondition.prototype.isValid = function () {
  48685. switch (this.operator) {
  48686. case ValueCondition.IsGreater:
  48687. return this._effectiveTarget[this._property] > this.value;
  48688. case ValueCondition.IsLesser:
  48689. return this._effectiveTarget[this._property] < this.value;
  48690. case ValueCondition.IsEqual:
  48691. case ValueCondition.IsDifferent:
  48692. var check;
  48693. if (this.value.equals) {
  48694. check = this.value.equals(this._effectiveTarget[this._property]);
  48695. }
  48696. else {
  48697. check = this.value === this._effectiveTarget[this._property];
  48698. }
  48699. return this.operator === ValueCondition.IsEqual ? check : !check;
  48700. }
  48701. return false;
  48702. };
  48703. ValueCondition.prototype.serialize = function () {
  48704. return this._serialize({
  48705. name: "ValueCondition",
  48706. properties: [
  48707. BABYLON.Action._GetTargetProperty(this._target),
  48708. { name: "propertyPath", value: this.propertyPath },
  48709. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  48710. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  48711. ]
  48712. });
  48713. };
  48714. ValueCondition.GetOperatorName = function (operator) {
  48715. switch (operator) {
  48716. case ValueCondition._IsEqual: return "IsEqual";
  48717. case ValueCondition._IsDifferent: return "IsDifferent";
  48718. case ValueCondition._IsGreater: return "IsGreater";
  48719. case ValueCondition._IsLesser: return "IsLesser";
  48720. default: return "";
  48721. }
  48722. };
  48723. // Statics
  48724. ValueCondition._IsEqual = 0;
  48725. ValueCondition._IsDifferent = 1;
  48726. ValueCondition._IsGreater = 2;
  48727. ValueCondition._IsLesser = 3;
  48728. return ValueCondition;
  48729. }(Condition));
  48730. BABYLON.ValueCondition = ValueCondition;
  48731. var PredicateCondition = /** @class */ (function (_super) {
  48732. __extends(PredicateCondition, _super);
  48733. function PredicateCondition(actionManager, predicate) {
  48734. var _this = _super.call(this, actionManager) || this;
  48735. _this.predicate = predicate;
  48736. return _this;
  48737. }
  48738. PredicateCondition.prototype.isValid = function () {
  48739. return this.predicate();
  48740. };
  48741. return PredicateCondition;
  48742. }(Condition));
  48743. BABYLON.PredicateCondition = PredicateCondition;
  48744. var StateCondition = /** @class */ (function (_super) {
  48745. __extends(StateCondition, _super);
  48746. function StateCondition(actionManager, target, value) {
  48747. var _this = _super.call(this, actionManager) || this;
  48748. _this.value = value;
  48749. _this._target = target;
  48750. return _this;
  48751. }
  48752. // Methods
  48753. StateCondition.prototype.isValid = function () {
  48754. return this._target.state === this.value;
  48755. };
  48756. StateCondition.prototype.serialize = function () {
  48757. return this._serialize({
  48758. name: "StateCondition",
  48759. properties: [
  48760. BABYLON.Action._GetTargetProperty(this._target),
  48761. { name: "value", value: this.value }
  48762. ]
  48763. });
  48764. };
  48765. return StateCondition;
  48766. }(Condition));
  48767. BABYLON.StateCondition = StateCondition;
  48768. })(BABYLON || (BABYLON = {}));
  48769. //# sourceMappingURL=babylon.condition.js.map
  48770. "use strict";
  48771. var BABYLON;
  48772. (function (BABYLON) {
  48773. var Action = /** @class */ (function () {
  48774. function Action(triggerOptions, condition) {
  48775. this.triggerOptions = triggerOptions;
  48776. this.onBeforeExecuteObservable = new BABYLON.Observable();
  48777. if (triggerOptions.parameter) {
  48778. this.trigger = triggerOptions.trigger;
  48779. this._triggerParameter = triggerOptions.parameter;
  48780. }
  48781. else {
  48782. this.trigger = triggerOptions;
  48783. }
  48784. this._nextActiveAction = this;
  48785. this._condition = condition;
  48786. }
  48787. // Methods
  48788. Action.prototype._prepare = function () {
  48789. };
  48790. Action.prototype.getTriggerParameter = function () {
  48791. return this._triggerParameter;
  48792. };
  48793. Action.prototype._executeCurrent = function (evt) {
  48794. if (this._nextActiveAction._condition) {
  48795. var condition = this._nextActiveAction._condition;
  48796. var currentRenderId = this._actionManager.getScene().getRenderId();
  48797. // We cache the current evaluation for the current frame
  48798. if (condition._evaluationId === currentRenderId) {
  48799. if (!condition._currentResult) {
  48800. return;
  48801. }
  48802. }
  48803. else {
  48804. condition._evaluationId = currentRenderId;
  48805. if (!condition.isValid()) {
  48806. condition._currentResult = false;
  48807. return;
  48808. }
  48809. condition._currentResult = true;
  48810. }
  48811. }
  48812. this.onBeforeExecuteObservable.notifyObservers(this);
  48813. this._nextActiveAction.execute(evt);
  48814. this.skipToNextActiveAction();
  48815. };
  48816. Action.prototype.execute = function (evt) {
  48817. };
  48818. Action.prototype.skipToNextActiveAction = function () {
  48819. if (this._nextActiveAction._child) {
  48820. if (!this._nextActiveAction._child._actionManager) {
  48821. this._nextActiveAction._child._actionManager = this._actionManager;
  48822. }
  48823. this._nextActiveAction = this._nextActiveAction._child;
  48824. }
  48825. else {
  48826. this._nextActiveAction = this;
  48827. }
  48828. };
  48829. Action.prototype.then = function (action) {
  48830. this._child = action;
  48831. action._actionManager = this._actionManager;
  48832. action._prepare();
  48833. return action;
  48834. };
  48835. Action.prototype._getProperty = function (propertyPath) {
  48836. return this._actionManager._getProperty(propertyPath);
  48837. };
  48838. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  48839. return this._actionManager._getEffectiveTarget(target, propertyPath);
  48840. };
  48841. Action.prototype.serialize = function (parent) {
  48842. };
  48843. // Called by BABYLON.Action objects in serialize(...). Internal use
  48844. Action.prototype._serialize = function (serializedAction, parent) {
  48845. var serializationObject = {
  48846. type: 1,
  48847. children: [],
  48848. name: serializedAction.name,
  48849. properties: serializedAction.properties || []
  48850. };
  48851. // Serialize child
  48852. if (this._child) {
  48853. this._child.serialize(serializationObject);
  48854. }
  48855. // Check if "this" has a condition
  48856. if (this._condition) {
  48857. var serializedCondition = this._condition.serialize();
  48858. serializedCondition.children.push(serializationObject);
  48859. if (parent) {
  48860. parent.children.push(serializedCondition);
  48861. }
  48862. return serializedCondition;
  48863. }
  48864. if (parent) {
  48865. parent.children.push(serializationObject);
  48866. }
  48867. return serializationObject;
  48868. };
  48869. Action._SerializeValueAsString = function (value) {
  48870. if (typeof value === "number") {
  48871. return value.toString();
  48872. }
  48873. if (typeof value === "boolean") {
  48874. return value ? "true" : "false";
  48875. }
  48876. if (value instanceof BABYLON.Vector2) {
  48877. return value.x + ", " + value.y;
  48878. }
  48879. if (value instanceof BABYLON.Vector3) {
  48880. return value.x + ", " + value.y + ", " + value.z;
  48881. }
  48882. if (value instanceof BABYLON.Color3) {
  48883. return value.r + ", " + value.g + ", " + value.b;
  48884. }
  48885. if (value instanceof BABYLON.Color4) {
  48886. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  48887. }
  48888. return value; // string
  48889. };
  48890. Action._GetTargetProperty = function (target) {
  48891. return {
  48892. name: "target",
  48893. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  48894. : target instanceof BABYLON.Light ? "LightProperties"
  48895. : target instanceof BABYLON.Camera ? "CameraProperties"
  48896. : "SceneProperties",
  48897. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  48898. };
  48899. };
  48900. return Action;
  48901. }());
  48902. BABYLON.Action = Action;
  48903. })(BABYLON || (BABYLON = {}));
  48904. //# sourceMappingURL=babylon.action.js.map
  48905. "use strict";
  48906. var BABYLON;
  48907. (function (BABYLON) {
  48908. /**
  48909. * ActionEvent is the event beint sent when an action is triggered.
  48910. */
  48911. var ActionEvent = /** @class */ (function () {
  48912. /**
  48913. * @param source The mesh or sprite that triggered the action.
  48914. * @param pointerX The X mouse cursor position at the time of the event
  48915. * @param pointerY The Y mouse cursor position at the time of the event
  48916. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  48917. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  48918. */
  48919. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  48920. this.source = source;
  48921. this.pointerX = pointerX;
  48922. this.pointerY = pointerY;
  48923. this.meshUnderPointer = meshUnderPointer;
  48924. this.sourceEvent = sourceEvent;
  48925. this.additionalData = additionalData;
  48926. }
  48927. /**
  48928. * Helper function to auto-create an ActionEvent from a source mesh.
  48929. * @param source The source mesh that triggered the event
  48930. * @param evt {Event} The original (browser) event
  48931. */
  48932. ActionEvent.CreateNew = function (source, evt, additionalData) {
  48933. var scene = source.getScene();
  48934. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  48935. };
  48936. /**
  48937. * Helper function to auto-create an ActionEvent from a source mesh.
  48938. * @param source The source sprite that triggered the event
  48939. * @param scene Scene associated with the sprite
  48940. * @param evt {Event} The original (browser) event
  48941. */
  48942. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  48943. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  48944. };
  48945. /**
  48946. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  48947. * @param scene the scene where the event occurred
  48948. * @param evt {Event} The original (browser) event
  48949. */
  48950. ActionEvent.CreateNewFromScene = function (scene, evt) {
  48951. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  48952. };
  48953. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  48954. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  48955. };
  48956. return ActionEvent;
  48957. }());
  48958. BABYLON.ActionEvent = ActionEvent;
  48959. /**
  48960. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  48961. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  48962. */
  48963. var ActionManager = /** @class */ (function () {
  48964. function ActionManager(scene) {
  48965. // Members
  48966. this.actions = new Array();
  48967. this.hoverCursor = '';
  48968. this._scene = scene;
  48969. scene._actionManagers.push(this);
  48970. }
  48971. Object.defineProperty(ActionManager, "NothingTrigger", {
  48972. get: function () {
  48973. return ActionManager._NothingTrigger;
  48974. },
  48975. enumerable: true,
  48976. configurable: true
  48977. });
  48978. Object.defineProperty(ActionManager, "OnPickTrigger", {
  48979. get: function () {
  48980. return ActionManager._OnPickTrigger;
  48981. },
  48982. enumerable: true,
  48983. configurable: true
  48984. });
  48985. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  48986. get: function () {
  48987. return ActionManager._OnLeftPickTrigger;
  48988. },
  48989. enumerable: true,
  48990. configurable: true
  48991. });
  48992. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  48993. get: function () {
  48994. return ActionManager._OnRightPickTrigger;
  48995. },
  48996. enumerable: true,
  48997. configurable: true
  48998. });
  48999. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  49000. get: function () {
  49001. return ActionManager._OnCenterPickTrigger;
  49002. },
  49003. enumerable: true,
  49004. configurable: true
  49005. });
  49006. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  49007. get: function () {
  49008. return ActionManager._OnPickDownTrigger;
  49009. },
  49010. enumerable: true,
  49011. configurable: true
  49012. });
  49013. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  49014. get: function () {
  49015. return ActionManager._OnDoublePickTrigger;
  49016. },
  49017. enumerable: true,
  49018. configurable: true
  49019. });
  49020. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  49021. get: function () {
  49022. return ActionManager._OnPickUpTrigger;
  49023. },
  49024. enumerable: true,
  49025. configurable: true
  49026. });
  49027. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  49028. /// This trigger will only be raised if you also declared a OnPickDown
  49029. get: function () {
  49030. return ActionManager._OnPickOutTrigger;
  49031. },
  49032. enumerable: true,
  49033. configurable: true
  49034. });
  49035. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  49036. get: function () {
  49037. return ActionManager._OnLongPressTrigger;
  49038. },
  49039. enumerable: true,
  49040. configurable: true
  49041. });
  49042. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  49043. get: function () {
  49044. return ActionManager._OnPointerOverTrigger;
  49045. },
  49046. enumerable: true,
  49047. configurable: true
  49048. });
  49049. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  49050. get: function () {
  49051. return ActionManager._OnPointerOutTrigger;
  49052. },
  49053. enumerable: true,
  49054. configurable: true
  49055. });
  49056. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  49057. get: function () {
  49058. return ActionManager._OnEveryFrameTrigger;
  49059. },
  49060. enumerable: true,
  49061. configurable: true
  49062. });
  49063. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  49064. get: function () {
  49065. return ActionManager._OnIntersectionEnterTrigger;
  49066. },
  49067. enumerable: true,
  49068. configurable: true
  49069. });
  49070. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  49071. get: function () {
  49072. return ActionManager._OnIntersectionExitTrigger;
  49073. },
  49074. enumerable: true,
  49075. configurable: true
  49076. });
  49077. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  49078. get: function () {
  49079. return ActionManager._OnKeyDownTrigger;
  49080. },
  49081. enumerable: true,
  49082. configurable: true
  49083. });
  49084. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  49085. get: function () {
  49086. return ActionManager._OnKeyUpTrigger;
  49087. },
  49088. enumerable: true,
  49089. configurable: true
  49090. });
  49091. // Methods
  49092. ActionManager.prototype.dispose = function () {
  49093. var index = this._scene._actionManagers.indexOf(this);
  49094. for (var i = 0; i < this.actions.length; i++) {
  49095. var action = this.actions[i];
  49096. ActionManager.Triggers[action.trigger]--;
  49097. if (ActionManager.Triggers[action.trigger] === 0) {
  49098. delete ActionManager.Triggers[action.trigger];
  49099. }
  49100. }
  49101. if (index > -1) {
  49102. this._scene._actionManagers.splice(index, 1);
  49103. }
  49104. };
  49105. ActionManager.prototype.getScene = function () {
  49106. return this._scene;
  49107. };
  49108. /**
  49109. * Does this action manager handles actions of any of the given triggers
  49110. * @param {number[]} triggers - the triggers to be tested
  49111. * @return {boolean} whether one (or more) of the triggers is handeled
  49112. */
  49113. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  49114. for (var index = 0; index < this.actions.length; index++) {
  49115. var action = this.actions[index];
  49116. if (triggers.indexOf(action.trigger) > -1) {
  49117. return true;
  49118. }
  49119. }
  49120. return false;
  49121. };
  49122. /**
  49123. * Does this action manager handles actions of a given trigger
  49124. * @param {number} trigger - the trigger to be tested
  49125. * @return {boolean} whether the trigger is handeled
  49126. */
  49127. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  49128. for (var index = 0; index < this.actions.length; index++) {
  49129. var action = this.actions[index];
  49130. if (action.trigger === trigger) {
  49131. return true;
  49132. }
  49133. }
  49134. return false;
  49135. };
  49136. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  49137. /**
  49138. * Does this action manager has pointer triggers
  49139. * @return {boolean} whether or not it has pointer triggers
  49140. */
  49141. get: function () {
  49142. for (var index = 0; index < this.actions.length; index++) {
  49143. var action = this.actions[index];
  49144. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  49145. return true;
  49146. }
  49147. }
  49148. return false;
  49149. },
  49150. enumerable: true,
  49151. configurable: true
  49152. });
  49153. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  49154. /**
  49155. * Does this action manager has pick triggers
  49156. * @return {boolean} whether or not it has pick triggers
  49157. */
  49158. get: function () {
  49159. for (var index = 0; index < this.actions.length; index++) {
  49160. var action = this.actions[index];
  49161. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  49162. return true;
  49163. }
  49164. }
  49165. return false;
  49166. },
  49167. enumerable: true,
  49168. configurable: true
  49169. });
  49170. Object.defineProperty(ActionManager, "HasTriggers", {
  49171. /**
  49172. * Does exist one action manager with at least one trigger
  49173. * @return {boolean} whether or not it exists one action manager with one trigger
  49174. **/
  49175. get: function () {
  49176. for (var t in ActionManager.Triggers) {
  49177. if (ActionManager.Triggers.hasOwnProperty(t)) {
  49178. return true;
  49179. }
  49180. }
  49181. return false;
  49182. },
  49183. enumerable: true,
  49184. configurable: true
  49185. });
  49186. Object.defineProperty(ActionManager, "HasPickTriggers", {
  49187. /**
  49188. * Does exist one action manager with at least one pick trigger
  49189. * @return {boolean} whether or not it exists one action manager with one pick trigger
  49190. **/
  49191. get: function () {
  49192. for (var t in ActionManager.Triggers) {
  49193. if (ActionManager.Triggers.hasOwnProperty(t)) {
  49194. var t_int = parseInt(t);
  49195. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  49196. return true;
  49197. }
  49198. }
  49199. }
  49200. return false;
  49201. },
  49202. enumerable: true,
  49203. configurable: true
  49204. });
  49205. /**
  49206. * Does exist one action manager that handles actions of a given trigger
  49207. * @param {number} trigger - the trigger to be tested
  49208. * @return {boolean} whether the trigger is handeled by at least one action manager
  49209. **/
  49210. ActionManager.HasSpecificTrigger = function (trigger) {
  49211. for (var t in ActionManager.Triggers) {
  49212. if (ActionManager.Triggers.hasOwnProperty(t)) {
  49213. var t_int = parseInt(t);
  49214. if (t_int === trigger) {
  49215. return true;
  49216. }
  49217. }
  49218. }
  49219. return false;
  49220. };
  49221. /**
  49222. * Registers an action to this action manager
  49223. * @param {BABYLON.Action} action - the action to be registered
  49224. * @return {BABYLON.Action} the action amended (prepared) after registration
  49225. */
  49226. ActionManager.prototype.registerAction = function (action) {
  49227. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  49228. if (this.getScene().actionManager !== this) {
  49229. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  49230. return null;
  49231. }
  49232. }
  49233. this.actions.push(action);
  49234. if (ActionManager.Triggers[action.trigger]) {
  49235. ActionManager.Triggers[action.trigger]++;
  49236. }
  49237. else {
  49238. ActionManager.Triggers[action.trigger] = 1;
  49239. }
  49240. action._actionManager = this;
  49241. action._prepare();
  49242. return action;
  49243. };
  49244. /**
  49245. * Unregisters an action to this action manager
  49246. * @param action The action to be unregistered
  49247. * @return whether the action has been unregistered
  49248. */
  49249. ActionManager.prototype.unregisterAction = function (action) {
  49250. var index = this.actions.indexOf(action);
  49251. if (index !== -1) {
  49252. this.actions.splice(index, 1);
  49253. ActionManager.Triggers[action.trigger] -= 1;
  49254. if (ActionManager.Triggers[action.trigger] === 0) {
  49255. delete ActionManager.Triggers[action.trigger];
  49256. }
  49257. delete action._actionManager;
  49258. return true;
  49259. }
  49260. return false;
  49261. };
  49262. /**
  49263. * Process a specific trigger
  49264. * @param {number} trigger - the trigger to process
  49265. * @param evt {BABYLON.ActionEvent} the event details to be processed
  49266. */
  49267. ActionManager.prototype.processTrigger = function (trigger, evt) {
  49268. for (var index = 0; index < this.actions.length; index++) {
  49269. var action = this.actions[index];
  49270. if (action.trigger === trigger) {
  49271. if (evt) {
  49272. if (trigger === ActionManager.OnKeyUpTrigger
  49273. || trigger === ActionManager.OnKeyDownTrigger) {
  49274. var parameter = action.getTriggerParameter();
  49275. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  49276. if (!parameter.toLowerCase) {
  49277. continue;
  49278. }
  49279. var lowerCase = parameter.toLowerCase();
  49280. if (lowerCase !== evt.sourceEvent.key) {
  49281. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  49282. var actualkey = String.fromCharCode(unicode).toLowerCase();
  49283. if (actualkey !== lowerCase) {
  49284. continue;
  49285. }
  49286. }
  49287. }
  49288. }
  49289. }
  49290. action._executeCurrent(evt);
  49291. }
  49292. }
  49293. };
  49294. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  49295. var properties = propertyPath.split(".");
  49296. for (var index = 0; index < properties.length - 1; index++) {
  49297. target = target[properties[index]];
  49298. }
  49299. return target;
  49300. };
  49301. ActionManager.prototype._getProperty = function (propertyPath) {
  49302. var properties = propertyPath.split(".");
  49303. return properties[properties.length - 1];
  49304. };
  49305. ActionManager.prototype.serialize = function (name) {
  49306. var root = {
  49307. children: new Array(),
  49308. name: name,
  49309. type: 3,
  49310. properties: new Array() // Empty for root but required
  49311. };
  49312. for (var i = 0; i < this.actions.length; i++) {
  49313. var triggerObject = {
  49314. type: 0,
  49315. children: new Array(),
  49316. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  49317. properties: new Array()
  49318. };
  49319. var triggerOptions = this.actions[i].triggerOptions;
  49320. if (triggerOptions && typeof triggerOptions !== "number") {
  49321. if (triggerOptions.parameter instanceof BABYLON.Node) {
  49322. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  49323. }
  49324. else {
  49325. var parameter = {};
  49326. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  49327. if (triggerOptions.parameter.mesh) {
  49328. parameter._meshId = triggerOptions.parameter.mesh.id;
  49329. }
  49330. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  49331. }
  49332. }
  49333. // Serialize child action, recursively
  49334. this.actions[i].serialize(triggerObject);
  49335. // Add serialized trigger
  49336. root.children.push(triggerObject);
  49337. }
  49338. return root;
  49339. };
  49340. ActionManager.Parse = function (parsedActions, object, scene) {
  49341. var actionManager = new ActionManager(scene);
  49342. if (object === null)
  49343. scene.actionManager = actionManager;
  49344. else
  49345. object.actionManager = actionManager;
  49346. // instanciate a new object
  49347. var instanciate = function (name, params) {
  49348. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  49349. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  49350. newInstance.constructor.apply(newInstance, params);
  49351. return newInstance;
  49352. };
  49353. var parseParameter = function (name, value, target, propertyPath) {
  49354. if (propertyPath === null) {
  49355. // String, boolean or float
  49356. var floatValue = parseFloat(value);
  49357. if (value === "true" || value === "false")
  49358. return value === "true";
  49359. else
  49360. return isNaN(floatValue) ? value : floatValue;
  49361. }
  49362. var effectiveTarget = propertyPath.split(".");
  49363. var values = value.split(",");
  49364. // Get effective Target
  49365. for (var i = 0; i < effectiveTarget.length; i++) {
  49366. target = target[effectiveTarget[i]];
  49367. }
  49368. // Return appropriate value with its type
  49369. if (typeof (target) === "boolean")
  49370. return values[0] === "true";
  49371. if (typeof (target) === "string")
  49372. return values[0];
  49373. // Parameters with multiple values such as Vector3 etc.
  49374. var split = new Array();
  49375. for (var i = 0; i < values.length; i++)
  49376. split.push(parseFloat(values[i]));
  49377. if (target instanceof BABYLON.Vector3)
  49378. return BABYLON.Vector3.FromArray(split);
  49379. if (target instanceof BABYLON.Vector4)
  49380. return BABYLON.Vector4.FromArray(split);
  49381. if (target instanceof BABYLON.Color3)
  49382. return BABYLON.Color3.FromArray(split);
  49383. if (target instanceof BABYLON.Color4)
  49384. return BABYLON.Color4.FromArray(split);
  49385. return parseFloat(values[0]);
  49386. };
  49387. // traverse graph per trigger
  49388. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  49389. if (combineArray === void 0) { combineArray = null; }
  49390. if (parsedAction.detached)
  49391. return;
  49392. var parameters = new Array();
  49393. var target = null;
  49394. var propertyPath = null;
  49395. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  49396. // Parameters
  49397. if (parsedAction.type === 2)
  49398. parameters.push(actionManager);
  49399. else
  49400. parameters.push(trigger);
  49401. if (combine) {
  49402. var actions = new Array();
  49403. for (var j = 0; j < parsedAction.combine.length; j++) {
  49404. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  49405. }
  49406. parameters.push(actions);
  49407. }
  49408. else {
  49409. for (var i = 0; i < parsedAction.properties.length; i++) {
  49410. var value = parsedAction.properties[i].value;
  49411. var name = parsedAction.properties[i].name;
  49412. var targetType = parsedAction.properties[i].targetType;
  49413. if (name === "target")
  49414. if (targetType !== null && targetType === "SceneProperties")
  49415. value = target = scene;
  49416. else
  49417. value = target = scene.getNodeByName(value);
  49418. else if (name === "parent")
  49419. value = scene.getNodeByName(value);
  49420. else if (name === "sound")
  49421. value = scene.getSoundByName(value);
  49422. else if (name !== "propertyPath") {
  49423. if (parsedAction.type === 2 && name === "operator")
  49424. value = BABYLON.ValueCondition[value];
  49425. else
  49426. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  49427. }
  49428. else {
  49429. propertyPath = value;
  49430. }
  49431. parameters.push(value);
  49432. }
  49433. }
  49434. if (combineArray === null) {
  49435. parameters.push(condition);
  49436. }
  49437. else {
  49438. parameters.push(null);
  49439. }
  49440. // If interpolate value action
  49441. if (parsedAction.name === "InterpolateValueAction") {
  49442. var param = parameters[parameters.length - 2];
  49443. parameters[parameters.length - 1] = param;
  49444. parameters[parameters.length - 2] = condition;
  49445. }
  49446. // Action or condition(s) and not CombineAction
  49447. var newAction = instanciate(parsedAction.name, parameters);
  49448. if (newAction instanceof BABYLON.Condition && condition !== null) {
  49449. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  49450. if (action)
  49451. action.then(nothing);
  49452. else
  49453. actionManager.registerAction(nothing);
  49454. action = nothing;
  49455. }
  49456. if (combineArray === null) {
  49457. if (newAction instanceof BABYLON.Condition) {
  49458. condition = newAction;
  49459. newAction = action;
  49460. }
  49461. else {
  49462. condition = null;
  49463. if (action)
  49464. action.then(newAction);
  49465. else
  49466. actionManager.registerAction(newAction);
  49467. }
  49468. }
  49469. else {
  49470. combineArray.push(newAction);
  49471. }
  49472. for (var i = 0; i < parsedAction.children.length; i++)
  49473. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  49474. };
  49475. // triggers
  49476. for (var i = 0; i < parsedActions.children.length; i++) {
  49477. var triggerParams;
  49478. var trigger = parsedActions.children[i];
  49479. if (trigger.properties.length > 0) {
  49480. var param = trigger.properties[0].value;
  49481. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  49482. if (value._meshId) {
  49483. value.mesh = scene.getMeshByID(value._meshId);
  49484. }
  49485. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  49486. }
  49487. else
  49488. triggerParams = ActionManager[trigger.name];
  49489. for (var j = 0; j < trigger.children.length; j++) {
  49490. if (!trigger.detached)
  49491. traverse(trigger.children[j], triggerParams, null, null);
  49492. }
  49493. }
  49494. };
  49495. ActionManager.GetTriggerName = function (trigger) {
  49496. switch (trigger) {
  49497. case 0: return "NothingTrigger";
  49498. case 1: return "OnPickTrigger";
  49499. case 2: return "OnLeftPickTrigger";
  49500. case 3: return "OnRightPickTrigger";
  49501. case 4: return "OnCenterPickTrigger";
  49502. case 5: return "OnPickDownTrigger";
  49503. case 6: return "OnPickUpTrigger";
  49504. case 7: return "OnLongPressTrigger";
  49505. case 8: return "OnPointerOverTrigger";
  49506. case 9: return "OnPointerOutTrigger";
  49507. case 10: return "OnEveryFrameTrigger";
  49508. case 11: return "OnIntersectionEnterTrigger";
  49509. case 12: return "OnIntersectionExitTrigger";
  49510. case 13: return "OnKeyDownTrigger";
  49511. case 14: return "OnKeyUpTrigger";
  49512. case 15: return "OnPickOutTrigger";
  49513. default: return "";
  49514. }
  49515. };
  49516. // Statics
  49517. ActionManager._NothingTrigger = 0;
  49518. ActionManager._OnPickTrigger = 1;
  49519. ActionManager._OnLeftPickTrigger = 2;
  49520. ActionManager._OnRightPickTrigger = 3;
  49521. ActionManager._OnCenterPickTrigger = 4;
  49522. ActionManager._OnPickDownTrigger = 5;
  49523. ActionManager._OnDoublePickTrigger = 6;
  49524. ActionManager._OnPickUpTrigger = 7;
  49525. ActionManager._OnLongPressTrigger = 8;
  49526. ActionManager._OnPointerOverTrigger = 9;
  49527. ActionManager._OnPointerOutTrigger = 10;
  49528. ActionManager._OnEveryFrameTrigger = 11;
  49529. ActionManager._OnIntersectionEnterTrigger = 12;
  49530. ActionManager._OnIntersectionExitTrigger = 13;
  49531. ActionManager._OnKeyDownTrigger = 14;
  49532. ActionManager._OnKeyUpTrigger = 15;
  49533. ActionManager._OnPickOutTrigger = 16;
  49534. ActionManager.Triggers = {};
  49535. return ActionManager;
  49536. }());
  49537. BABYLON.ActionManager = ActionManager;
  49538. })(BABYLON || (BABYLON = {}));
  49539. //# sourceMappingURL=babylon.actionManager.js.map
  49540. "use strict";
  49541. var BABYLON;
  49542. (function (BABYLON) {
  49543. var InterpolateValueAction = /** @class */ (function (_super) {
  49544. __extends(InterpolateValueAction, _super);
  49545. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  49546. if (duration === void 0) { duration = 1000; }
  49547. var _this = _super.call(this, triggerOptions, condition) || this;
  49548. _this.propertyPath = propertyPath;
  49549. _this.value = value;
  49550. _this.duration = duration;
  49551. _this.stopOtherAnimations = stopOtherAnimations;
  49552. _this.onInterpolationDone = onInterpolationDone;
  49553. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  49554. _this._target = _this._effectiveTarget = target;
  49555. return _this;
  49556. }
  49557. InterpolateValueAction.prototype._prepare = function () {
  49558. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49559. this._property = this._getProperty(this.propertyPath);
  49560. };
  49561. InterpolateValueAction.prototype.execute = function () {
  49562. var _this = this;
  49563. var scene = this._actionManager.getScene();
  49564. var keys = [
  49565. {
  49566. frame: 0,
  49567. value: this._effectiveTarget[this._property]
  49568. }, {
  49569. frame: 100,
  49570. value: this.value
  49571. }
  49572. ];
  49573. var dataType;
  49574. if (typeof this.value === "number") {
  49575. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  49576. }
  49577. else if (this.value instanceof BABYLON.Color3) {
  49578. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  49579. }
  49580. else if (this.value instanceof BABYLON.Vector3) {
  49581. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  49582. }
  49583. else if (this.value instanceof BABYLON.Matrix) {
  49584. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  49585. }
  49586. else if (this.value instanceof BABYLON.Quaternion) {
  49587. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  49588. }
  49589. else {
  49590. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  49591. return;
  49592. }
  49593. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  49594. animation.setKeys(keys);
  49595. if (this.stopOtherAnimations) {
  49596. scene.stopAnimation(this._effectiveTarget);
  49597. }
  49598. var wrapper = function () {
  49599. _this.onInterpolationDoneObservable.notifyObservers(_this);
  49600. if (_this.onInterpolationDone) {
  49601. _this.onInterpolationDone();
  49602. }
  49603. };
  49604. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  49605. };
  49606. InterpolateValueAction.prototype.serialize = function (parent) {
  49607. return _super.prototype._serialize.call(this, {
  49608. name: "InterpolateValueAction",
  49609. properties: [
  49610. BABYLON.Action._GetTargetProperty(this._target),
  49611. { name: "propertyPath", value: this.propertyPath },
  49612. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  49613. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  49614. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  49615. ]
  49616. }, parent);
  49617. };
  49618. return InterpolateValueAction;
  49619. }(BABYLON.Action));
  49620. BABYLON.InterpolateValueAction = InterpolateValueAction;
  49621. })(BABYLON || (BABYLON = {}));
  49622. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  49623. "use strict";
  49624. var BABYLON;
  49625. (function (BABYLON) {
  49626. var SwitchBooleanAction = /** @class */ (function (_super) {
  49627. __extends(SwitchBooleanAction, _super);
  49628. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  49629. var _this = _super.call(this, triggerOptions, condition) || this;
  49630. _this.propertyPath = propertyPath;
  49631. _this._target = _this._effectiveTarget = target;
  49632. return _this;
  49633. }
  49634. SwitchBooleanAction.prototype._prepare = function () {
  49635. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49636. this._property = this._getProperty(this.propertyPath);
  49637. };
  49638. SwitchBooleanAction.prototype.execute = function () {
  49639. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  49640. };
  49641. SwitchBooleanAction.prototype.serialize = function (parent) {
  49642. return _super.prototype._serialize.call(this, {
  49643. name: "SwitchBooleanAction",
  49644. properties: [
  49645. BABYLON.Action._GetTargetProperty(this._target),
  49646. { name: "propertyPath", value: this.propertyPath }
  49647. ]
  49648. }, parent);
  49649. };
  49650. return SwitchBooleanAction;
  49651. }(BABYLON.Action));
  49652. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  49653. var SetStateAction = /** @class */ (function (_super) {
  49654. __extends(SetStateAction, _super);
  49655. function SetStateAction(triggerOptions, target, value, condition) {
  49656. var _this = _super.call(this, triggerOptions, condition) || this;
  49657. _this.value = value;
  49658. _this._target = target;
  49659. return _this;
  49660. }
  49661. SetStateAction.prototype.execute = function () {
  49662. this._target.state = this.value;
  49663. };
  49664. SetStateAction.prototype.serialize = function (parent) {
  49665. return _super.prototype._serialize.call(this, {
  49666. name: "SetStateAction",
  49667. properties: [
  49668. BABYLON.Action._GetTargetProperty(this._target),
  49669. { name: "value", value: this.value }
  49670. ]
  49671. }, parent);
  49672. };
  49673. return SetStateAction;
  49674. }(BABYLON.Action));
  49675. BABYLON.SetStateAction = SetStateAction;
  49676. var SetValueAction = /** @class */ (function (_super) {
  49677. __extends(SetValueAction, _super);
  49678. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  49679. var _this = _super.call(this, triggerOptions, condition) || this;
  49680. _this.propertyPath = propertyPath;
  49681. _this.value = value;
  49682. _this._target = _this._effectiveTarget = target;
  49683. return _this;
  49684. }
  49685. SetValueAction.prototype._prepare = function () {
  49686. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49687. this._property = this._getProperty(this.propertyPath);
  49688. };
  49689. SetValueAction.prototype.execute = function () {
  49690. this._effectiveTarget[this._property] = this.value;
  49691. if (this._target.markAsDirty) {
  49692. this._target.markAsDirty(this._property);
  49693. }
  49694. };
  49695. SetValueAction.prototype.serialize = function (parent) {
  49696. return _super.prototype._serialize.call(this, {
  49697. name: "SetValueAction",
  49698. properties: [
  49699. BABYLON.Action._GetTargetProperty(this._target),
  49700. { name: "propertyPath", value: this.propertyPath },
  49701. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  49702. ]
  49703. }, parent);
  49704. };
  49705. return SetValueAction;
  49706. }(BABYLON.Action));
  49707. BABYLON.SetValueAction = SetValueAction;
  49708. var IncrementValueAction = /** @class */ (function (_super) {
  49709. __extends(IncrementValueAction, _super);
  49710. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  49711. var _this = _super.call(this, triggerOptions, condition) || this;
  49712. _this.propertyPath = propertyPath;
  49713. _this.value = value;
  49714. _this._target = _this._effectiveTarget = target;
  49715. return _this;
  49716. }
  49717. IncrementValueAction.prototype._prepare = function () {
  49718. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  49719. this._property = this._getProperty(this.propertyPath);
  49720. if (typeof this._effectiveTarget[this._property] !== "number") {
  49721. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  49722. }
  49723. };
  49724. IncrementValueAction.prototype.execute = function () {
  49725. this._effectiveTarget[this._property] += this.value;
  49726. if (this._target.markAsDirty) {
  49727. this._target.markAsDirty(this._property);
  49728. }
  49729. };
  49730. IncrementValueAction.prototype.serialize = function (parent) {
  49731. return _super.prototype._serialize.call(this, {
  49732. name: "IncrementValueAction",
  49733. properties: [
  49734. BABYLON.Action._GetTargetProperty(this._target),
  49735. { name: "propertyPath", value: this.propertyPath },
  49736. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  49737. ]
  49738. }, parent);
  49739. };
  49740. return IncrementValueAction;
  49741. }(BABYLON.Action));
  49742. BABYLON.IncrementValueAction = IncrementValueAction;
  49743. var PlayAnimationAction = /** @class */ (function (_super) {
  49744. __extends(PlayAnimationAction, _super);
  49745. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  49746. var _this = _super.call(this, triggerOptions, condition) || this;
  49747. _this.from = from;
  49748. _this.to = to;
  49749. _this.loop = loop;
  49750. _this._target = target;
  49751. return _this;
  49752. }
  49753. PlayAnimationAction.prototype._prepare = function () {
  49754. };
  49755. PlayAnimationAction.prototype.execute = function () {
  49756. var scene = this._actionManager.getScene();
  49757. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  49758. };
  49759. PlayAnimationAction.prototype.serialize = function (parent) {
  49760. return _super.prototype._serialize.call(this, {
  49761. name: "PlayAnimationAction",
  49762. properties: [
  49763. BABYLON.Action._GetTargetProperty(this._target),
  49764. { name: "from", value: String(this.from) },
  49765. { name: "to", value: String(this.to) },
  49766. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  49767. ]
  49768. }, parent);
  49769. };
  49770. return PlayAnimationAction;
  49771. }(BABYLON.Action));
  49772. BABYLON.PlayAnimationAction = PlayAnimationAction;
  49773. var StopAnimationAction = /** @class */ (function (_super) {
  49774. __extends(StopAnimationAction, _super);
  49775. function StopAnimationAction(triggerOptions, target, condition) {
  49776. var _this = _super.call(this, triggerOptions, condition) || this;
  49777. _this._target = target;
  49778. return _this;
  49779. }
  49780. StopAnimationAction.prototype._prepare = function () {
  49781. };
  49782. StopAnimationAction.prototype.execute = function () {
  49783. var scene = this._actionManager.getScene();
  49784. scene.stopAnimation(this._target);
  49785. };
  49786. StopAnimationAction.prototype.serialize = function (parent) {
  49787. return _super.prototype._serialize.call(this, {
  49788. name: "StopAnimationAction",
  49789. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  49790. }, parent);
  49791. };
  49792. return StopAnimationAction;
  49793. }(BABYLON.Action));
  49794. BABYLON.StopAnimationAction = StopAnimationAction;
  49795. var DoNothingAction = /** @class */ (function (_super) {
  49796. __extends(DoNothingAction, _super);
  49797. function DoNothingAction(triggerOptions, condition) {
  49798. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  49799. return _super.call(this, triggerOptions, condition) || this;
  49800. }
  49801. DoNothingAction.prototype.execute = function () {
  49802. };
  49803. DoNothingAction.prototype.serialize = function (parent) {
  49804. return _super.prototype._serialize.call(this, {
  49805. name: "DoNothingAction",
  49806. properties: []
  49807. }, parent);
  49808. };
  49809. return DoNothingAction;
  49810. }(BABYLON.Action));
  49811. BABYLON.DoNothingAction = DoNothingAction;
  49812. var CombineAction = /** @class */ (function (_super) {
  49813. __extends(CombineAction, _super);
  49814. function CombineAction(triggerOptions, children, condition) {
  49815. var _this = _super.call(this, triggerOptions, condition) || this;
  49816. _this.children = children;
  49817. return _this;
  49818. }
  49819. CombineAction.prototype._prepare = function () {
  49820. for (var index = 0; index < this.children.length; index++) {
  49821. this.children[index]._actionManager = this._actionManager;
  49822. this.children[index]._prepare();
  49823. }
  49824. };
  49825. CombineAction.prototype.execute = function (evt) {
  49826. for (var index = 0; index < this.children.length; index++) {
  49827. this.children[index].execute(evt);
  49828. }
  49829. };
  49830. CombineAction.prototype.serialize = function (parent) {
  49831. var serializationObject = _super.prototype._serialize.call(this, {
  49832. name: "CombineAction",
  49833. properties: [],
  49834. combine: []
  49835. }, parent);
  49836. for (var i = 0; i < this.children.length; i++) {
  49837. serializationObject.combine.push(this.children[i].serialize(null));
  49838. }
  49839. return serializationObject;
  49840. };
  49841. return CombineAction;
  49842. }(BABYLON.Action));
  49843. BABYLON.CombineAction = CombineAction;
  49844. var ExecuteCodeAction = /** @class */ (function (_super) {
  49845. __extends(ExecuteCodeAction, _super);
  49846. function ExecuteCodeAction(triggerOptions, func, condition) {
  49847. var _this = _super.call(this, triggerOptions, condition) || this;
  49848. _this.func = func;
  49849. return _this;
  49850. }
  49851. ExecuteCodeAction.prototype.execute = function (evt) {
  49852. this.func(evt);
  49853. };
  49854. return ExecuteCodeAction;
  49855. }(BABYLON.Action));
  49856. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  49857. var SetParentAction = /** @class */ (function (_super) {
  49858. __extends(SetParentAction, _super);
  49859. function SetParentAction(triggerOptions, target, parent, condition) {
  49860. var _this = _super.call(this, triggerOptions, condition) || this;
  49861. _this._target = target;
  49862. _this._parent = parent;
  49863. return _this;
  49864. }
  49865. SetParentAction.prototype._prepare = function () {
  49866. };
  49867. SetParentAction.prototype.execute = function () {
  49868. if (this._target.parent === this._parent) {
  49869. return;
  49870. }
  49871. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  49872. invertParentWorldMatrix.invert();
  49873. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  49874. this._target.parent = this._parent;
  49875. };
  49876. SetParentAction.prototype.serialize = function (parent) {
  49877. return _super.prototype._serialize.call(this, {
  49878. name: "SetParentAction",
  49879. properties: [
  49880. BABYLON.Action._GetTargetProperty(this._target),
  49881. BABYLON.Action._GetTargetProperty(this._parent),
  49882. ]
  49883. }, parent);
  49884. };
  49885. return SetParentAction;
  49886. }(BABYLON.Action));
  49887. BABYLON.SetParentAction = SetParentAction;
  49888. var PlaySoundAction = /** @class */ (function (_super) {
  49889. __extends(PlaySoundAction, _super);
  49890. function PlaySoundAction(triggerOptions, sound, condition) {
  49891. var _this = _super.call(this, triggerOptions, condition) || this;
  49892. _this._sound = sound;
  49893. return _this;
  49894. }
  49895. PlaySoundAction.prototype._prepare = function () {
  49896. };
  49897. PlaySoundAction.prototype.execute = function () {
  49898. if (this._sound !== undefined)
  49899. this._sound.play();
  49900. };
  49901. PlaySoundAction.prototype.serialize = function (parent) {
  49902. return _super.prototype._serialize.call(this, {
  49903. name: "PlaySoundAction",
  49904. properties: [{ name: "sound", value: this._sound.name }]
  49905. }, parent);
  49906. };
  49907. return PlaySoundAction;
  49908. }(BABYLON.Action));
  49909. BABYLON.PlaySoundAction = PlaySoundAction;
  49910. var StopSoundAction = /** @class */ (function (_super) {
  49911. __extends(StopSoundAction, _super);
  49912. function StopSoundAction(triggerOptions, sound, condition) {
  49913. var _this = _super.call(this, triggerOptions, condition) || this;
  49914. _this._sound = sound;
  49915. return _this;
  49916. }
  49917. StopSoundAction.prototype._prepare = function () {
  49918. };
  49919. StopSoundAction.prototype.execute = function () {
  49920. if (this._sound !== undefined)
  49921. this._sound.stop();
  49922. };
  49923. StopSoundAction.prototype.serialize = function (parent) {
  49924. return _super.prototype._serialize.call(this, {
  49925. name: "StopSoundAction",
  49926. properties: [{ name: "sound", value: this._sound.name }]
  49927. }, parent);
  49928. };
  49929. return StopSoundAction;
  49930. }(BABYLON.Action));
  49931. BABYLON.StopSoundAction = StopSoundAction;
  49932. })(BABYLON || (BABYLON = {}));
  49933. //# sourceMappingURL=babylon.directActions.js.map
  49934. "use strict";
  49935. var BABYLON;
  49936. (function (BABYLON) {
  49937. var SpriteManager = /** @class */ (function () {
  49938. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  49939. if (epsilon === void 0) { epsilon = 0.01; }
  49940. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  49941. this.name = name;
  49942. this.sprites = new Array();
  49943. this.renderingGroupId = 0;
  49944. this.layerMask = 0x0FFFFFFF;
  49945. this.fogEnabled = true;
  49946. this.isPickable = false;
  49947. /**
  49948. * An event triggered when the manager is disposed.
  49949. * @type {BABYLON.Observable}
  49950. */
  49951. this.onDisposeObservable = new BABYLON.Observable();
  49952. this._vertexBuffers = {};
  49953. this._capacity = capacity;
  49954. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  49955. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49956. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  49957. if (cellSize.width && cellSize.height) {
  49958. this.cellWidth = cellSize.width;
  49959. this.cellHeight = cellSize.height;
  49960. }
  49961. else if (cellSize !== undefined) {
  49962. this.cellWidth = cellSize;
  49963. this.cellHeight = cellSize;
  49964. }
  49965. else {
  49966. return;
  49967. }
  49968. this._epsilon = epsilon;
  49969. this._scene = scene;
  49970. this._scene.spriteManagers.push(this);
  49971. var indices = [];
  49972. var index = 0;
  49973. for (var count = 0; count < capacity; count++) {
  49974. indices.push(index);
  49975. indices.push(index + 1);
  49976. indices.push(index + 2);
  49977. indices.push(index);
  49978. indices.push(index + 2);
  49979. indices.push(index + 3);
  49980. index += 4;
  49981. }
  49982. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  49983. // VBO
  49984. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  49985. this._vertexData = new Float32Array(capacity * 16 * 4);
  49986. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  49987. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  49988. var options = this._buffer.createVertexBuffer("options", 4, 4);
  49989. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  49990. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  49991. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  49992. this._vertexBuffers["options"] = options;
  49993. this._vertexBuffers["cellInfo"] = cellInfo;
  49994. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  49995. // Effects
  49996. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  49997. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  49998. }
  49999. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  50000. set: function (callback) {
  50001. if (this._onDisposeObserver) {
  50002. this.onDisposeObservable.remove(this._onDisposeObserver);
  50003. }
  50004. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  50005. },
  50006. enumerable: true,
  50007. configurable: true
  50008. });
  50009. Object.defineProperty(SpriteManager.prototype, "texture", {
  50010. get: function () {
  50011. return this._spriteTexture;
  50012. },
  50013. set: function (value) {
  50014. this._spriteTexture = value;
  50015. },
  50016. enumerable: true,
  50017. configurable: true
  50018. });
  50019. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  50020. var arrayOffset = index * 16;
  50021. if (offsetX === 0)
  50022. offsetX = this._epsilon;
  50023. else if (offsetX === 1)
  50024. offsetX = 1 - this._epsilon;
  50025. if (offsetY === 0)
  50026. offsetY = this._epsilon;
  50027. else if (offsetY === 1)
  50028. offsetY = 1 - this._epsilon;
  50029. this._vertexData[arrayOffset] = sprite.position.x;
  50030. this._vertexData[arrayOffset + 1] = sprite.position.y;
  50031. this._vertexData[arrayOffset + 2] = sprite.position.z;
  50032. this._vertexData[arrayOffset + 3] = sprite.angle;
  50033. this._vertexData[arrayOffset + 4] = sprite.width;
  50034. this._vertexData[arrayOffset + 5] = sprite.height;
  50035. this._vertexData[arrayOffset + 6] = offsetX;
  50036. this._vertexData[arrayOffset + 7] = offsetY;
  50037. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  50038. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  50039. var offset = (sprite.cellIndex / rowSize) >> 0;
  50040. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  50041. this._vertexData[arrayOffset + 11] = offset;
  50042. // Color
  50043. this._vertexData[arrayOffset + 12] = sprite.color.r;
  50044. this._vertexData[arrayOffset + 13] = sprite.color.g;
  50045. this._vertexData[arrayOffset + 14] = sprite.color.b;
  50046. this._vertexData[arrayOffset + 15] = sprite.color.a;
  50047. };
  50048. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  50049. var count = Math.min(this._capacity, this.sprites.length);
  50050. var min = BABYLON.Vector3.Zero();
  50051. var max = BABYLON.Vector3.Zero();
  50052. var distance = Number.MAX_VALUE;
  50053. var currentSprite = null;
  50054. var cameraSpacePosition = BABYLON.Vector3.Zero();
  50055. var cameraView = camera.getViewMatrix();
  50056. for (var index = 0; index < count; index++) {
  50057. var sprite = this.sprites[index];
  50058. if (!sprite) {
  50059. continue;
  50060. }
  50061. if (predicate) {
  50062. if (!predicate(sprite)) {
  50063. continue;
  50064. }
  50065. }
  50066. else if (!sprite.isPickable) {
  50067. continue;
  50068. }
  50069. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  50070. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  50071. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  50072. if (ray.intersectsBoxMinMax(min, max)) {
  50073. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  50074. if (distance > currentDistance) {
  50075. distance = currentDistance;
  50076. currentSprite = sprite;
  50077. if (fastCheck) {
  50078. break;
  50079. }
  50080. }
  50081. }
  50082. }
  50083. if (currentSprite) {
  50084. var result = new BABYLON.PickingInfo();
  50085. result.hit = true;
  50086. result.pickedSprite = currentSprite;
  50087. result.distance = distance;
  50088. return result;
  50089. }
  50090. return null;
  50091. };
  50092. SpriteManager.prototype.render = function () {
  50093. // Check
  50094. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  50095. return;
  50096. var engine = this._scene.getEngine();
  50097. var baseSize = this._spriteTexture.getBaseSize();
  50098. // Sprites
  50099. var deltaTime = engine.getDeltaTime();
  50100. var max = Math.min(this._capacity, this.sprites.length);
  50101. var rowSize = baseSize.width / this.cellWidth;
  50102. var offset = 0;
  50103. for (var index = 0; index < max; index++) {
  50104. var sprite = this.sprites[index];
  50105. if (!sprite) {
  50106. continue;
  50107. }
  50108. sprite._animate(deltaTime);
  50109. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  50110. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  50111. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  50112. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  50113. }
  50114. this._buffer.update(this._vertexData);
  50115. // Render
  50116. var effect = this._effectBase;
  50117. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  50118. effect = this._effectFog;
  50119. }
  50120. engine.enableEffect(effect);
  50121. var viewMatrix = this._scene.getViewMatrix();
  50122. effect.setTexture("diffuseSampler", this._spriteTexture);
  50123. effect.setMatrix("view", viewMatrix);
  50124. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  50125. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  50126. // Fog
  50127. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  50128. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  50129. effect.setColor3("vFogColor", this._scene.fogColor);
  50130. }
  50131. // VBOs
  50132. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  50133. // Draw order
  50134. engine.setDepthFunctionToLessOrEqual();
  50135. effect.setBool("alphaTest", true);
  50136. engine.setColorWrite(false);
  50137. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  50138. engine.setColorWrite(true);
  50139. effect.setBool("alphaTest", false);
  50140. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  50141. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  50142. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  50143. };
  50144. SpriteManager.prototype.dispose = function () {
  50145. if (this._buffer) {
  50146. this._buffer.dispose();
  50147. this._buffer = null;
  50148. }
  50149. if (this._indexBuffer) {
  50150. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  50151. this._indexBuffer = null;
  50152. }
  50153. if (this._spriteTexture) {
  50154. this._spriteTexture.dispose();
  50155. this._spriteTexture = null;
  50156. }
  50157. // Remove from scene
  50158. var index = this._scene.spriteManagers.indexOf(this);
  50159. this._scene.spriteManagers.splice(index, 1);
  50160. // Callback
  50161. this.onDisposeObservable.notifyObservers(this);
  50162. this.onDisposeObservable.clear();
  50163. };
  50164. return SpriteManager;
  50165. }());
  50166. BABYLON.SpriteManager = SpriteManager;
  50167. })(BABYLON || (BABYLON = {}));
  50168. //# sourceMappingURL=babylon.spriteManager.js.map
  50169. "use strict";
  50170. var BABYLON;
  50171. (function (BABYLON) {
  50172. var Sprite = /** @class */ (function () {
  50173. function Sprite(name, manager) {
  50174. this.name = name;
  50175. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  50176. this.width = 1.0;
  50177. this.height = 1.0;
  50178. this.angle = 0;
  50179. this.cellIndex = 0;
  50180. this.invertU = 0;
  50181. this.invertV = 0;
  50182. this.animations = new Array();
  50183. this.isPickable = false;
  50184. this._animationStarted = false;
  50185. this._loopAnimation = false;
  50186. this._fromIndex = 0;
  50187. this._toIndex = 0;
  50188. this._delay = 0;
  50189. this._direction = 1;
  50190. this._time = 0;
  50191. this._manager = manager;
  50192. this._manager.sprites.push(this);
  50193. this.position = BABYLON.Vector3.Zero();
  50194. }
  50195. Object.defineProperty(Sprite.prototype, "size", {
  50196. get: function () {
  50197. return this.width;
  50198. },
  50199. set: function (value) {
  50200. this.width = value;
  50201. this.height = value;
  50202. },
  50203. enumerable: true,
  50204. configurable: true
  50205. });
  50206. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  50207. this._fromIndex = from;
  50208. this._toIndex = to;
  50209. this._loopAnimation = loop;
  50210. this._delay = delay;
  50211. this._animationStarted = true;
  50212. this._direction = from < to ? 1 : -1;
  50213. this.cellIndex = from;
  50214. this._time = 0;
  50215. this._onAnimationEnd = onAnimationEnd;
  50216. };
  50217. Sprite.prototype.stopAnimation = function () {
  50218. this._animationStarted = false;
  50219. };
  50220. Sprite.prototype._animate = function (deltaTime) {
  50221. if (!this._animationStarted)
  50222. return;
  50223. this._time += deltaTime;
  50224. if (this._time > this._delay) {
  50225. this._time = this._time % this._delay;
  50226. this.cellIndex += this._direction;
  50227. if (this.cellIndex > this._toIndex) {
  50228. if (this._loopAnimation) {
  50229. this.cellIndex = this._fromIndex;
  50230. }
  50231. else {
  50232. this.cellIndex = this._toIndex;
  50233. this._animationStarted = false;
  50234. if (this._onAnimationEnd) {
  50235. this._onAnimationEnd();
  50236. }
  50237. if (this.disposeWhenFinishedAnimating) {
  50238. this.dispose();
  50239. }
  50240. }
  50241. }
  50242. }
  50243. };
  50244. Sprite.prototype.dispose = function () {
  50245. for (var i = 0; i < this._manager.sprites.length; i++) {
  50246. if (this._manager.sprites[i] == this) {
  50247. this._manager.sprites.splice(i, 1);
  50248. }
  50249. }
  50250. };
  50251. return Sprite;
  50252. }());
  50253. BABYLON.Sprite = Sprite;
  50254. })(BABYLON || (BABYLON = {}));
  50255. //# sourceMappingURL=babylon.sprite.js.map
  50256. "use strict";
  50257. var BABYLON;
  50258. (function (BABYLON) {
  50259. var IntersectionInfo = /** @class */ (function () {
  50260. function IntersectionInfo(bu, bv, distance) {
  50261. this.bu = bu;
  50262. this.bv = bv;
  50263. this.distance = distance;
  50264. this.faceId = 0;
  50265. this.subMeshId = 0;
  50266. }
  50267. return IntersectionInfo;
  50268. }());
  50269. BABYLON.IntersectionInfo = IntersectionInfo;
  50270. var PickingInfo = /** @class */ (function () {
  50271. function PickingInfo() {
  50272. this.hit = false;
  50273. this.distance = 0;
  50274. this.pickedPoint = null;
  50275. this.pickedMesh = null;
  50276. this.bu = 0;
  50277. this.bv = 0;
  50278. this.faceId = -1;
  50279. this.subMeshId = 0;
  50280. this.pickedSprite = null;
  50281. }
  50282. // Methods
  50283. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  50284. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  50285. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  50286. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  50287. return null;
  50288. }
  50289. var indices = this.pickedMesh.getIndices();
  50290. if (!indices) {
  50291. return null;
  50292. }
  50293. var result;
  50294. if (useVerticesNormals) {
  50295. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  50296. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  50297. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  50298. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  50299. normal0 = normal0.scale(this.bu);
  50300. normal1 = normal1.scale(this.bv);
  50301. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  50302. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  50303. }
  50304. else {
  50305. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  50306. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  50307. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  50308. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  50309. var p1p2 = vertex1.subtract(vertex2);
  50310. var p3p2 = vertex3.subtract(vertex2);
  50311. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  50312. }
  50313. if (useWorldCoordinates) {
  50314. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  50315. }
  50316. return BABYLON.Vector3.Normalize(result);
  50317. };
  50318. PickingInfo.prototype.getTextureCoordinates = function () {
  50319. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  50320. return null;
  50321. }
  50322. var indices = this.pickedMesh.getIndices();
  50323. if (!indices) {
  50324. return null;
  50325. }
  50326. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  50327. if (!uvs) {
  50328. return null;
  50329. }
  50330. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  50331. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  50332. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  50333. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  50334. uv1 = uv1.scale(this.bu);
  50335. uv2 = uv2.scale(this.bv);
  50336. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  50337. };
  50338. return PickingInfo;
  50339. }());
  50340. BABYLON.PickingInfo = PickingInfo;
  50341. })(BABYLON || (BABYLON = {}));
  50342. //# sourceMappingURL=babylon.pickingInfo.js.map
  50343. "use strict";
  50344. var BABYLON;
  50345. (function (BABYLON) {
  50346. var Ray = /** @class */ (function () {
  50347. function Ray(origin, direction, length) {
  50348. if (length === void 0) { length = Number.MAX_VALUE; }
  50349. this.origin = origin;
  50350. this.direction = direction;
  50351. this.length = length;
  50352. }
  50353. // Methods
  50354. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  50355. var d = 0.0;
  50356. var maxValue = Number.MAX_VALUE;
  50357. var inv;
  50358. var min;
  50359. var max;
  50360. var temp;
  50361. if (Math.abs(this.direction.x) < 0.0000001) {
  50362. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  50363. return false;
  50364. }
  50365. }
  50366. else {
  50367. inv = 1.0 / this.direction.x;
  50368. min = (minimum.x - this.origin.x) * inv;
  50369. max = (maximum.x - this.origin.x) * inv;
  50370. if (max === -Infinity) {
  50371. max = Infinity;
  50372. }
  50373. if (min > max) {
  50374. temp = min;
  50375. min = max;
  50376. max = temp;
  50377. }
  50378. d = Math.max(min, d);
  50379. maxValue = Math.min(max, maxValue);
  50380. if (d > maxValue) {
  50381. return false;
  50382. }
  50383. }
  50384. if (Math.abs(this.direction.y) < 0.0000001) {
  50385. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  50386. return false;
  50387. }
  50388. }
  50389. else {
  50390. inv = 1.0 / this.direction.y;
  50391. min = (minimum.y - this.origin.y) * inv;
  50392. max = (maximum.y - this.origin.y) * inv;
  50393. if (max === -Infinity) {
  50394. max = Infinity;
  50395. }
  50396. if (min > max) {
  50397. temp = min;
  50398. min = max;
  50399. max = temp;
  50400. }
  50401. d = Math.max(min, d);
  50402. maxValue = Math.min(max, maxValue);
  50403. if (d > maxValue) {
  50404. return false;
  50405. }
  50406. }
  50407. if (Math.abs(this.direction.z) < 0.0000001) {
  50408. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  50409. return false;
  50410. }
  50411. }
  50412. else {
  50413. inv = 1.0 / this.direction.z;
  50414. min = (minimum.z - this.origin.z) * inv;
  50415. max = (maximum.z - this.origin.z) * inv;
  50416. if (max === -Infinity) {
  50417. max = Infinity;
  50418. }
  50419. if (min > max) {
  50420. temp = min;
  50421. min = max;
  50422. max = temp;
  50423. }
  50424. d = Math.max(min, d);
  50425. maxValue = Math.min(max, maxValue);
  50426. if (d > maxValue) {
  50427. return false;
  50428. }
  50429. }
  50430. return true;
  50431. };
  50432. Ray.prototype.intersectsBox = function (box) {
  50433. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  50434. };
  50435. Ray.prototype.intersectsSphere = function (sphere) {
  50436. var x = sphere.center.x - this.origin.x;
  50437. var y = sphere.center.y - this.origin.y;
  50438. var z = sphere.center.z - this.origin.z;
  50439. var pyth = (x * x) + (y * y) + (z * z);
  50440. var rr = sphere.radius * sphere.radius;
  50441. if (pyth <= rr) {
  50442. return true;
  50443. }
  50444. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  50445. if (dot < 0.0) {
  50446. return false;
  50447. }
  50448. var temp = pyth - (dot * dot);
  50449. return temp <= rr;
  50450. };
  50451. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  50452. if (!this._edge1) {
  50453. this._edge1 = BABYLON.Vector3.Zero();
  50454. this._edge2 = BABYLON.Vector3.Zero();
  50455. this._pvec = BABYLON.Vector3.Zero();
  50456. this._tvec = BABYLON.Vector3.Zero();
  50457. this._qvec = BABYLON.Vector3.Zero();
  50458. }
  50459. vertex1.subtractToRef(vertex0, this._edge1);
  50460. vertex2.subtractToRef(vertex0, this._edge2);
  50461. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  50462. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  50463. if (det === 0) {
  50464. return null;
  50465. }
  50466. var invdet = 1 / det;
  50467. this.origin.subtractToRef(vertex0, this._tvec);
  50468. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  50469. if (bu < 0 || bu > 1.0) {
  50470. return null;
  50471. }
  50472. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  50473. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  50474. if (bv < 0 || bu + bv > 1.0) {
  50475. return null;
  50476. }
  50477. //check if the distance is longer than the predefined length.
  50478. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  50479. if (distance > this.length) {
  50480. return null;
  50481. }
  50482. return new BABYLON.IntersectionInfo(bu, bv, distance);
  50483. };
  50484. Ray.prototype.intersectsPlane = function (plane) {
  50485. var distance;
  50486. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  50487. if (Math.abs(result1) < 9.99999997475243E-07) {
  50488. return null;
  50489. }
  50490. else {
  50491. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  50492. distance = (-plane.d - result2) / result1;
  50493. if (distance < 0.0) {
  50494. if (distance < -9.99999997475243E-07) {
  50495. return null;
  50496. }
  50497. else {
  50498. return 0;
  50499. }
  50500. }
  50501. return distance;
  50502. }
  50503. };
  50504. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  50505. var tm = BABYLON.Tmp.Matrix[0];
  50506. mesh.getWorldMatrix().invertToRef(tm);
  50507. if (this._tmpRay) {
  50508. Ray.TransformToRef(this, tm, this._tmpRay);
  50509. }
  50510. else {
  50511. this._tmpRay = Ray.Transform(this, tm);
  50512. }
  50513. return mesh.intersects(this._tmpRay, fastCheck);
  50514. };
  50515. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  50516. if (results) {
  50517. results.length = 0;
  50518. }
  50519. else {
  50520. results = [];
  50521. }
  50522. for (var i = 0; i < meshes.length; i++) {
  50523. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  50524. if (pickInfo.hit) {
  50525. results.push(pickInfo);
  50526. }
  50527. }
  50528. results.sort(this._comparePickingInfo);
  50529. return results;
  50530. };
  50531. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  50532. if (pickingInfoA.distance < pickingInfoB.distance) {
  50533. return -1;
  50534. }
  50535. else if (pickingInfoA.distance > pickingInfoB.distance) {
  50536. return 1;
  50537. }
  50538. else {
  50539. return 0;
  50540. }
  50541. };
  50542. /**
  50543. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  50544. * @param sega the first point of the segment to test the intersection against
  50545. * @param segb the second point of the segment to test the intersection against
  50546. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  50547. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  50548. */
  50549. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  50550. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  50551. var u = segb.subtract(sega);
  50552. var v = rsegb.subtract(this.origin);
  50553. var w = sega.subtract(this.origin);
  50554. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  50555. var b = BABYLON.Vector3.Dot(u, v);
  50556. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  50557. var d = BABYLON.Vector3.Dot(u, w);
  50558. var e = BABYLON.Vector3.Dot(v, w);
  50559. var D = a * c - b * b; // always >= 0
  50560. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  50561. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  50562. // compute the line parameters of the two closest points
  50563. if (D < Ray.smallnum) {
  50564. sN = 0.0; // force using point P0 on segment S1
  50565. sD = 1.0; // to prevent possible division by 0.0 later
  50566. tN = e;
  50567. tD = c;
  50568. }
  50569. else {
  50570. sN = (b * e - c * d);
  50571. tN = (a * e - b * d);
  50572. if (sN < 0.0) {
  50573. sN = 0.0;
  50574. tN = e;
  50575. tD = c;
  50576. }
  50577. else if (sN > sD) {
  50578. sN = sD;
  50579. tN = e + b;
  50580. tD = c;
  50581. }
  50582. }
  50583. if (tN < 0.0) {
  50584. tN = 0.0;
  50585. // recompute sc for this edge
  50586. if (-d < 0.0) {
  50587. sN = 0.0;
  50588. }
  50589. else if (-d > a)
  50590. sN = sD;
  50591. else {
  50592. sN = -d;
  50593. sD = a;
  50594. }
  50595. }
  50596. else if (tN > tD) {
  50597. tN = tD;
  50598. // recompute sc for this edge
  50599. if ((-d + b) < 0.0) {
  50600. sN = 0;
  50601. }
  50602. else if ((-d + b) > a) {
  50603. sN = sD;
  50604. }
  50605. else {
  50606. sN = (-d + b);
  50607. sD = a;
  50608. }
  50609. }
  50610. // finally do the division to get sc and tc
  50611. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  50612. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  50613. // get the difference of the two closest points
  50614. var qtc = v.multiplyByFloats(tc, tc, tc);
  50615. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  50616. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  50617. if (isIntersected) {
  50618. return qtc.length();
  50619. }
  50620. return -1;
  50621. };
  50622. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  50623. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  50624. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  50625. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  50626. this.direction.normalize();
  50627. return this;
  50628. };
  50629. // Statics
  50630. Ray.Zero = function () {
  50631. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  50632. };
  50633. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  50634. var result = Ray.Zero();
  50635. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  50636. };
  50637. /**
  50638. * 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
  50639. * transformed to the given world matrix.
  50640. * @param origin The origin point
  50641. * @param end The end point
  50642. * @param world a matrix to transform the ray to. Default is the identity matrix.
  50643. */
  50644. Ray.CreateNewFromTo = function (origin, end, world) {
  50645. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  50646. var direction = end.subtract(origin);
  50647. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  50648. direction.normalize();
  50649. return Ray.Transform(new Ray(origin, direction, length), world);
  50650. };
  50651. Ray.Transform = function (ray, matrix) {
  50652. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  50653. Ray.TransformToRef(ray, matrix, result);
  50654. return result;
  50655. };
  50656. Ray.TransformToRef = function (ray, matrix, result) {
  50657. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  50658. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  50659. result.length = ray.length;
  50660. var dir = result.direction;
  50661. var len = dir.length();
  50662. if (!(len === 0 || len === 1)) {
  50663. var num = 1.0 / len;
  50664. dir.x *= num;
  50665. dir.y *= num;
  50666. dir.z *= num;
  50667. result.length *= len;
  50668. }
  50669. };
  50670. Ray.smallnum = 0.00000001;
  50671. Ray.rayl = 10e8;
  50672. return Ray;
  50673. }());
  50674. BABYLON.Ray = Ray;
  50675. })(BABYLON || (BABYLON = {}));
  50676. //# sourceMappingURL=babylon.ray.js.map
  50677. "use strict";
  50678. var BABYLON;
  50679. (function (BABYLON) {
  50680. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  50681. if (boxMin.x > sphereCenter.x + sphereRadius)
  50682. return false;
  50683. if (sphereCenter.x - sphereRadius > boxMax.x)
  50684. return false;
  50685. if (boxMin.y > sphereCenter.y + sphereRadius)
  50686. return false;
  50687. if (sphereCenter.y - sphereRadius > boxMax.y)
  50688. return false;
  50689. if (boxMin.z > sphereCenter.z + sphereRadius)
  50690. return false;
  50691. if (sphereCenter.z - sphereRadius > boxMax.z)
  50692. return false;
  50693. return true;
  50694. };
  50695. var getLowestRoot = (function () {
  50696. var result = { root: 0, found: false };
  50697. return function (a, b, c, maxR) {
  50698. result.root = 0;
  50699. result.found = false;
  50700. var determinant = b * b - 4.0 * a * c;
  50701. if (determinant < 0)
  50702. return result;
  50703. var sqrtD = Math.sqrt(determinant);
  50704. var r1 = (-b - sqrtD) / (2.0 * a);
  50705. var r2 = (-b + sqrtD) / (2.0 * a);
  50706. if (r1 > r2) {
  50707. var temp = r2;
  50708. r2 = r1;
  50709. r1 = temp;
  50710. }
  50711. if (r1 > 0 && r1 < maxR) {
  50712. result.root = r1;
  50713. result.found = true;
  50714. return result;
  50715. }
  50716. if (r2 > 0 && r2 < maxR) {
  50717. result.root = r2;
  50718. result.found = true;
  50719. return result;
  50720. }
  50721. return result;
  50722. };
  50723. })();
  50724. var Collider = /** @class */ (function () {
  50725. function Collider() {
  50726. this._collisionPoint = BABYLON.Vector3.Zero();
  50727. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  50728. this._tempVector = BABYLON.Vector3.Zero();
  50729. this._tempVector2 = BABYLON.Vector3.Zero();
  50730. this._tempVector3 = BABYLON.Vector3.Zero();
  50731. this._tempVector4 = BABYLON.Vector3.Zero();
  50732. this._edge = BABYLON.Vector3.Zero();
  50733. this._baseToVertex = BABYLON.Vector3.Zero();
  50734. this._destinationPoint = BABYLON.Vector3.Zero();
  50735. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  50736. this._displacementVector = BABYLON.Vector3.Zero();
  50737. this._radius = BABYLON.Vector3.One();
  50738. this._retry = 0;
  50739. this._basePointWorld = BABYLON.Vector3.Zero();
  50740. this._velocityWorld = BABYLON.Vector3.Zero();
  50741. this._normalizedVelocity = BABYLON.Vector3.Zero();
  50742. this._collisionMask = -1;
  50743. }
  50744. Object.defineProperty(Collider.prototype, "collisionMask", {
  50745. get: function () {
  50746. return this._collisionMask;
  50747. },
  50748. set: function (mask) {
  50749. this._collisionMask = !isNaN(mask) ? mask : -1;
  50750. },
  50751. enumerable: true,
  50752. configurable: true
  50753. });
  50754. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  50755. /**
  50756. * Gets the plane normal used to compute the sliding response (in local space)
  50757. */
  50758. get: function () {
  50759. return this._slidePlaneNormal;
  50760. },
  50761. enumerable: true,
  50762. configurable: true
  50763. });
  50764. // Methods
  50765. Collider.prototype._initialize = function (source, dir, e) {
  50766. this._velocity = dir;
  50767. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  50768. this._basePoint = source;
  50769. source.multiplyToRef(this._radius, this._basePointWorld);
  50770. dir.multiplyToRef(this._radius, this._velocityWorld);
  50771. this._velocityWorldLength = this._velocityWorld.length();
  50772. this._epsilon = e;
  50773. this.collisionFound = false;
  50774. };
  50775. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  50776. pa.subtractToRef(point, this._tempVector);
  50777. pb.subtractToRef(point, this._tempVector2);
  50778. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  50779. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50780. if (d < 0)
  50781. return false;
  50782. pc.subtractToRef(point, this._tempVector3);
  50783. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  50784. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50785. if (d < 0)
  50786. return false;
  50787. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  50788. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  50789. return d >= 0;
  50790. };
  50791. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  50792. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  50793. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  50794. if (distance > this._velocityWorldLength + max + sphereRadius) {
  50795. return false;
  50796. }
  50797. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  50798. return false;
  50799. return true;
  50800. };
  50801. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  50802. var t0;
  50803. var embeddedInPlane = false;
  50804. //defensive programming, actually not needed.
  50805. if (!trianglePlaneArray) {
  50806. trianglePlaneArray = [];
  50807. }
  50808. if (!trianglePlaneArray[faceIndex]) {
  50809. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  50810. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  50811. }
  50812. var trianglePlane = trianglePlaneArray[faceIndex];
  50813. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  50814. return;
  50815. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  50816. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  50817. if (normalDotVelocity == 0) {
  50818. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  50819. return;
  50820. embeddedInPlane = true;
  50821. t0 = 0;
  50822. }
  50823. else {
  50824. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  50825. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  50826. if (t0 > t1) {
  50827. var temp = t1;
  50828. t1 = t0;
  50829. t0 = temp;
  50830. }
  50831. if (t0 > 1.0 || t1 < 0.0)
  50832. return;
  50833. if (t0 < 0)
  50834. t0 = 0;
  50835. if (t0 > 1.0)
  50836. t0 = 1.0;
  50837. }
  50838. this._collisionPoint.copyFromFloats(0, 0, 0);
  50839. var found = false;
  50840. var t = 1.0;
  50841. if (!embeddedInPlane) {
  50842. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  50843. this._velocity.scaleToRef(t0, this._tempVector);
  50844. this._planeIntersectionPoint.addInPlace(this._tempVector);
  50845. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  50846. found = true;
  50847. t = t0;
  50848. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  50849. }
  50850. }
  50851. if (!found) {
  50852. var velocitySquaredLength = this._velocity.lengthSquared();
  50853. var a = velocitySquaredLength;
  50854. this._basePoint.subtractToRef(p1, this._tempVector);
  50855. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50856. var c = this._tempVector.lengthSquared() - 1.0;
  50857. var lowestRoot = getLowestRoot(a, b, c, t);
  50858. if (lowestRoot.found) {
  50859. t = lowestRoot.root;
  50860. found = true;
  50861. this._collisionPoint.copyFrom(p1);
  50862. }
  50863. this._basePoint.subtractToRef(p2, this._tempVector);
  50864. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50865. c = this._tempVector.lengthSquared() - 1.0;
  50866. lowestRoot = getLowestRoot(a, b, c, t);
  50867. if (lowestRoot.found) {
  50868. t = lowestRoot.root;
  50869. found = true;
  50870. this._collisionPoint.copyFrom(p2);
  50871. }
  50872. this._basePoint.subtractToRef(p3, this._tempVector);
  50873. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  50874. c = this._tempVector.lengthSquared() - 1.0;
  50875. lowestRoot = getLowestRoot(a, b, c, t);
  50876. if (lowestRoot.found) {
  50877. t = lowestRoot.root;
  50878. found = true;
  50879. this._collisionPoint.copyFrom(p3);
  50880. }
  50881. p2.subtractToRef(p1, this._edge);
  50882. p1.subtractToRef(this._basePoint, this._baseToVertex);
  50883. var edgeSquaredLength = this._edge.lengthSquared();
  50884. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50885. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50886. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50887. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50888. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50889. lowestRoot = getLowestRoot(a, b, c, t);
  50890. if (lowestRoot.found) {
  50891. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50892. if (f >= 0.0 && f <= 1.0) {
  50893. t = lowestRoot.root;
  50894. found = true;
  50895. this._edge.scaleInPlace(f);
  50896. p1.addToRef(this._edge, this._collisionPoint);
  50897. }
  50898. }
  50899. p3.subtractToRef(p2, this._edge);
  50900. p2.subtractToRef(this._basePoint, this._baseToVertex);
  50901. edgeSquaredLength = this._edge.lengthSquared();
  50902. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50903. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50904. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50905. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50906. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50907. lowestRoot = getLowestRoot(a, b, c, t);
  50908. if (lowestRoot.found) {
  50909. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50910. if (f >= 0.0 && f <= 1.0) {
  50911. t = lowestRoot.root;
  50912. found = true;
  50913. this._edge.scaleInPlace(f);
  50914. p2.addToRef(this._edge, this._collisionPoint);
  50915. }
  50916. }
  50917. p1.subtractToRef(p3, this._edge);
  50918. p3.subtractToRef(this._basePoint, this._baseToVertex);
  50919. edgeSquaredLength = this._edge.lengthSquared();
  50920. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  50921. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  50922. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  50923. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  50924. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  50925. lowestRoot = getLowestRoot(a, b, c, t);
  50926. if (lowestRoot.found) {
  50927. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  50928. if (f >= 0.0 && f <= 1.0) {
  50929. t = lowestRoot.root;
  50930. found = true;
  50931. this._edge.scaleInPlace(f);
  50932. p3.addToRef(this._edge, this._collisionPoint);
  50933. }
  50934. }
  50935. }
  50936. if (found) {
  50937. var distToCollision = t * this._velocity.length();
  50938. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  50939. if (!this.intersectionPoint) {
  50940. this.intersectionPoint = this._collisionPoint.clone();
  50941. }
  50942. else {
  50943. this.intersectionPoint.copyFrom(this._collisionPoint);
  50944. }
  50945. this._nearestDistance = distToCollision;
  50946. this.collisionFound = true;
  50947. }
  50948. }
  50949. };
  50950. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  50951. for (var i = indexStart; i < indexEnd; i += 3) {
  50952. var p1 = pts[indices[i] - decal];
  50953. var p2 = pts[indices[i + 1] - decal];
  50954. var p3 = pts[indices[i + 2] - decal];
  50955. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  50956. }
  50957. };
  50958. Collider.prototype._getResponse = function (pos, vel) {
  50959. pos.addToRef(vel, this._destinationPoint);
  50960. vel.scaleInPlace((this._nearestDistance / vel.length()));
  50961. this._basePoint.addToRef(vel, pos);
  50962. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  50963. this._slidePlaneNormal.normalize();
  50964. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  50965. pos.addInPlace(this._displacementVector);
  50966. this.intersectionPoint.addInPlace(this._displacementVector);
  50967. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  50968. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  50969. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  50970. };
  50971. return Collider;
  50972. }());
  50973. BABYLON.Collider = Collider;
  50974. })(BABYLON || (BABYLON = {}));
  50975. //# sourceMappingURL=babylon.collider.js.map
  50976. "use strict";
  50977. var BABYLON;
  50978. (function (BABYLON) {
  50979. //WebWorker code will be inserted to this variable.
  50980. BABYLON.CollisionWorker = "";
  50981. var WorkerTaskType;
  50982. (function (WorkerTaskType) {
  50983. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  50984. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  50985. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  50986. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  50987. var WorkerReplyType;
  50988. (function (WorkerReplyType) {
  50989. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  50990. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  50991. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  50992. var CollisionCoordinatorWorker = /** @class */ (function () {
  50993. function CollisionCoordinatorWorker() {
  50994. var _this = this;
  50995. this._scaledPosition = BABYLON.Vector3.Zero();
  50996. this._scaledVelocity = BABYLON.Vector3.Zero();
  50997. this.onMeshUpdated = function (transformNode) {
  50998. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  50999. };
  51000. this.onGeometryUpdated = function (geometry) {
  51001. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  51002. };
  51003. this._afterRender = function () {
  51004. if (!_this._init)
  51005. return;
  51006. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  51007. return;
  51008. }
  51009. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  51010. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  51011. if (_this._runningUpdated > 4) {
  51012. return;
  51013. }
  51014. ++_this._runningUpdated;
  51015. var payload = {
  51016. updatedMeshes: _this._addUpdateMeshesList,
  51017. updatedGeometries: _this._addUpdateGeometriesList,
  51018. removedGeometries: _this._toRemoveGeometryArray,
  51019. removedMeshes: _this._toRemoveMeshesArray
  51020. };
  51021. var message = {
  51022. payload: payload,
  51023. taskType: WorkerTaskType.UPDATE
  51024. };
  51025. var serializable = [];
  51026. for (var id in payload.updatedGeometries) {
  51027. if (payload.updatedGeometries.hasOwnProperty(id)) {
  51028. //prepare transferables
  51029. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  51030. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  51031. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  51032. }
  51033. }
  51034. _this._worker.postMessage(message, serializable);
  51035. _this._addUpdateMeshesList = {};
  51036. _this._addUpdateGeometriesList = {};
  51037. _this._toRemoveGeometryArray = [];
  51038. _this._toRemoveMeshesArray = [];
  51039. };
  51040. this._onMessageFromWorker = function (e) {
  51041. var returnData = e.data;
  51042. if (returnData.error != WorkerReplyType.SUCCESS) {
  51043. //TODO what errors can be returned from the worker?
  51044. BABYLON.Tools.Warn("error returned from worker!");
  51045. return;
  51046. }
  51047. switch (returnData.taskType) {
  51048. case WorkerTaskType.INIT:
  51049. _this._init = true;
  51050. //Update the worked with ALL of the scene's current state
  51051. _this._scene.meshes.forEach(function (mesh) {
  51052. _this.onMeshAdded(mesh);
  51053. });
  51054. _this._scene.getGeometries().forEach(function (geometry) {
  51055. _this.onGeometryAdded(geometry);
  51056. });
  51057. break;
  51058. case WorkerTaskType.UPDATE:
  51059. _this._runningUpdated--;
  51060. break;
  51061. case WorkerTaskType.COLLIDE:
  51062. var returnPayload = returnData.payload;
  51063. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  51064. return;
  51065. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  51066. if (callback) {
  51067. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  51068. if (mesh) {
  51069. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  51070. }
  51071. }
  51072. //cleanup
  51073. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  51074. break;
  51075. }
  51076. };
  51077. this._collisionsCallbackArray = [];
  51078. this._init = false;
  51079. this._runningUpdated = 0;
  51080. this._addUpdateMeshesList = {};
  51081. this._addUpdateGeometriesList = {};
  51082. this._toRemoveGeometryArray = [];
  51083. this._toRemoveMeshesArray = [];
  51084. }
  51085. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  51086. if (!this._init)
  51087. return;
  51088. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  51089. return;
  51090. position.divideToRef(collider._radius, this._scaledPosition);
  51091. displacement.divideToRef(collider._radius, this._scaledVelocity);
  51092. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  51093. var payload = {
  51094. collider: {
  51095. position: this._scaledPosition.asArray(),
  51096. velocity: this._scaledVelocity.asArray(),
  51097. radius: collider._radius.asArray()
  51098. },
  51099. collisionId: collisionIndex,
  51100. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  51101. maximumRetry: maximumRetry
  51102. };
  51103. var message = {
  51104. payload: payload,
  51105. taskType: WorkerTaskType.COLLIDE
  51106. };
  51107. this._worker.postMessage(message);
  51108. };
  51109. CollisionCoordinatorWorker.prototype.init = function (scene) {
  51110. this._scene = scene;
  51111. this._scene.registerAfterRender(this._afterRender);
  51112. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  51113. this._worker = new Worker(workerUrl);
  51114. this._worker.onmessage = this._onMessageFromWorker;
  51115. var message = {
  51116. payload: {},
  51117. taskType: WorkerTaskType.INIT
  51118. };
  51119. this._worker.postMessage(message);
  51120. };
  51121. CollisionCoordinatorWorker.prototype.destroy = function () {
  51122. this._scene.unregisterAfterRender(this._afterRender);
  51123. this._worker.terminate();
  51124. };
  51125. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  51126. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  51127. this.onMeshUpdated(mesh);
  51128. };
  51129. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  51130. this._toRemoveMeshesArray.push(mesh.uniqueId);
  51131. };
  51132. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  51133. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  51134. geometry.onGeometryUpdated = this.onGeometryUpdated;
  51135. this.onGeometryUpdated(geometry);
  51136. };
  51137. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  51138. this._toRemoveGeometryArray.push(geometry.id);
  51139. };
  51140. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  51141. var submeshes = [];
  51142. if (mesh.subMeshes) {
  51143. submeshes = mesh.subMeshes.map(function (sm, idx) {
  51144. var boundingInfo = sm.getBoundingInfo();
  51145. return {
  51146. position: idx,
  51147. verticesStart: sm.verticesStart,
  51148. verticesCount: sm.verticesCount,
  51149. indexStart: sm.indexStart,
  51150. indexCount: sm.indexCount,
  51151. hasMaterial: !!sm.getMaterial(),
  51152. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  51153. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  51154. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  51155. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  51156. };
  51157. });
  51158. }
  51159. var geometryId = null;
  51160. if (mesh instanceof BABYLON.Mesh) {
  51161. var geometry = mesh.geometry;
  51162. geometryId = geometry ? geometry.id : null;
  51163. }
  51164. else if (mesh instanceof BABYLON.InstancedMesh) {
  51165. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  51166. geometryId = geometry ? geometry.id : null;
  51167. }
  51168. var boundingInfo = mesh.getBoundingInfo();
  51169. return {
  51170. uniqueId: mesh.uniqueId,
  51171. id: mesh.id,
  51172. name: mesh.name,
  51173. geometryId: geometryId,
  51174. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  51175. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  51176. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  51177. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  51178. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  51179. subMeshes: submeshes,
  51180. checkCollisions: mesh.checkCollisions
  51181. };
  51182. };
  51183. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  51184. return {
  51185. id: geometry.id,
  51186. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  51187. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  51188. indices: new Uint32Array(geometry.getIndices() || []),
  51189. };
  51190. };
  51191. return CollisionCoordinatorWorker;
  51192. }());
  51193. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  51194. var CollisionCoordinatorLegacy = /** @class */ (function () {
  51195. function CollisionCoordinatorLegacy() {
  51196. this._scaledPosition = BABYLON.Vector3.Zero();
  51197. this._scaledVelocity = BABYLON.Vector3.Zero();
  51198. this._finalPosition = BABYLON.Vector3.Zero();
  51199. }
  51200. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  51201. position.divideToRef(collider._radius, this._scaledPosition);
  51202. displacement.divideToRef(collider._radius, this._scaledVelocity);
  51203. collider.collidedMesh = null;
  51204. collider._retry = 0;
  51205. collider._initialVelocity = this._scaledVelocity;
  51206. collider._initialPosition = this._scaledPosition;
  51207. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  51208. this._finalPosition.multiplyInPlace(collider._radius);
  51209. //run the callback
  51210. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  51211. };
  51212. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  51213. this._scene = scene;
  51214. };
  51215. CollisionCoordinatorLegacy.prototype.destroy = function () {
  51216. //Legacy need no destruction method.
  51217. };
  51218. //No update in legacy mode
  51219. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  51220. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  51221. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  51222. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  51223. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  51224. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  51225. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  51226. if (excludedMesh === void 0) { excludedMesh = null; }
  51227. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  51228. if (collider._retry >= maximumRetry) {
  51229. finalPosition.copyFrom(position);
  51230. return;
  51231. }
  51232. // Check if this is a mesh else camera or -1
  51233. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  51234. collider._initialize(position, velocity, closeDistance);
  51235. // Check all meshes
  51236. for (var index = 0; index < this._scene.meshes.length; index++) {
  51237. var mesh = this._scene.meshes[index];
  51238. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  51239. mesh._checkCollision(collider);
  51240. }
  51241. }
  51242. if (!collider.collisionFound) {
  51243. position.addToRef(velocity, finalPosition);
  51244. return;
  51245. }
  51246. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  51247. collider._getResponse(position, velocity);
  51248. }
  51249. if (velocity.length() <= closeDistance) {
  51250. finalPosition.copyFrom(position);
  51251. return;
  51252. }
  51253. collider._retry++;
  51254. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  51255. };
  51256. return CollisionCoordinatorLegacy;
  51257. }());
  51258. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  51259. })(BABYLON || (BABYLON = {}));
  51260. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  51261. "use strict";
  51262. var BABYLON;
  51263. (function (BABYLON) {
  51264. /**
  51265. * A particle represents one of the element emitted by a particle system.
  51266. * This is mainly define by its coordinates, direction, velocity and age.
  51267. */
  51268. var Particle = /** @class */ (function () {
  51269. /**
  51270. * Creates a new instance of @see Particle
  51271. * @param particleSystem the particle system the particle belongs to
  51272. */
  51273. function Particle(
  51274. /**
  51275. * particleSystem the particle system the particle belongs to.
  51276. */
  51277. particleSystem) {
  51278. this.particleSystem = particleSystem;
  51279. /**
  51280. * The world position of the particle in the scene.
  51281. */
  51282. this.position = BABYLON.Vector3.Zero();
  51283. /**
  51284. * The world direction of the particle in the scene.
  51285. */
  51286. this.direction = BABYLON.Vector3.Zero();
  51287. /**
  51288. * The color of the particle.
  51289. */
  51290. this.color = new BABYLON.Color4(0, 0, 0, 0);
  51291. /**
  51292. * The color change of the particle per step.
  51293. */
  51294. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  51295. /**
  51296. * Defines how long will the life of the particle be.
  51297. */
  51298. this.lifeTime = 1.0;
  51299. /**
  51300. * The current age of the particle.
  51301. */
  51302. this.age = 0;
  51303. /**
  51304. * The current size of the particle.
  51305. */
  51306. this.size = 0;
  51307. /**
  51308. * The current angle of the particle.
  51309. */
  51310. this.angle = 0;
  51311. /**
  51312. * Defines how fast is the angle changing.
  51313. */
  51314. this.angularSpeed = 0;
  51315. /**
  51316. * Defines the cell index used by the particle to be rendered from a sprite.
  51317. */
  51318. this.cellIndex = 0;
  51319. this._currentFrameCounter = 0;
  51320. if (!this.particleSystem.isAnimationSheetEnabled) {
  51321. return;
  51322. }
  51323. this.updateCellInfoFromSystem();
  51324. }
  51325. Particle.prototype.updateCellInfoFromSystem = function () {
  51326. this.cellIndex = this.particleSystem.startSpriteCellID;
  51327. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  51328. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  51329. }
  51330. else {
  51331. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  51332. }
  51333. };
  51334. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  51335. // (ageOffset / scaledUpdateSpeed) / available cells
  51336. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  51337. this._currentFrameCounter += scaledUpdateSpeed;
  51338. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  51339. this._currentFrameCounter = 0;
  51340. this.cellIndex++;
  51341. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  51342. this.cellIndex = this.particleSystem.endSpriteCellID;
  51343. }
  51344. }
  51345. };
  51346. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  51347. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  51348. this.cellIndex++;
  51349. this._currentFrameCounter = 0;
  51350. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  51351. if (this.particleSystem.spriteCellLoop) {
  51352. this.cellIndex = this.particleSystem.startSpriteCellID;
  51353. }
  51354. else {
  51355. this.cellIndex = this.particleSystem.endSpriteCellID;
  51356. }
  51357. }
  51358. }
  51359. else {
  51360. this._currentFrameCounter++;
  51361. }
  51362. };
  51363. /**
  51364. * Copy the properties of particle to another one.
  51365. * @param other the particle to copy the information to.
  51366. */
  51367. Particle.prototype.copyTo = function (other) {
  51368. other.position.copyFrom(this.position);
  51369. other.direction.copyFrom(this.direction);
  51370. other.color.copyFrom(this.color);
  51371. other.colorStep.copyFrom(this.colorStep);
  51372. other.lifeTime = this.lifeTime;
  51373. other.age = this.age;
  51374. other.size = this.size;
  51375. other.angle = this.angle;
  51376. other.angularSpeed = this.angularSpeed;
  51377. other.particleSystem = this.particleSystem;
  51378. other.cellIndex = this.cellIndex;
  51379. };
  51380. return Particle;
  51381. }());
  51382. BABYLON.Particle = Particle;
  51383. })(BABYLON || (BABYLON = {}));
  51384. //# sourceMappingURL=babylon.particle.js.map
  51385. "use strict";
  51386. var BABYLON;
  51387. (function (BABYLON) {
  51388. /**
  51389. * This represents a particle system in Babylon.
  51390. * 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.
  51391. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  51392. * @example https://doc.babylonjs.com/babylon101/particles
  51393. */
  51394. var ParticleSystem = /** @class */ (function () {
  51395. /**
  51396. * Instantiates a particle system.
  51397. * 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.
  51398. * @param name The name of the particle system
  51399. * @param capacity The max number of particles alive at the same time
  51400. * @param scene The scene the particle system belongs to
  51401. * @param customEffect a custom effect used to change the way particles are rendered by default
  51402. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  51403. * @param epsilon Offset used to render the particles
  51404. */
  51405. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  51406. if (customEffect === void 0) { customEffect = null; }
  51407. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  51408. if (epsilon === void 0) { epsilon = 0.01; }
  51409. var _this = this;
  51410. /**
  51411. * List of animations used by the particle system.
  51412. */
  51413. this.animations = [];
  51414. /**
  51415. * The rendering group used by the Particle system to chose when to render.
  51416. */
  51417. this.renderingGroupId = 0;
  51418. /**
  51419. * The emitter represents the Mesh or position we are attaching the particle system to.
  51420. */
  51421. this.emitter = null;
  51422. /**
  51423. * The maximum number of particles to emit per frame
  51424. */
  51425. this.emitRate = 10;
  51426. /**
  51427. * If you want to launch only a few particles at once, that can be done, as well.
  51428. */
  51429. this.manualEmitCount = -1;
  51430. /**
  51431. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  51432. */
  51433. this.updateSpeed = 0.01;
  51434. /**
  51435. * The amount of time the particle system is running (depends of the overall update speed).
  51436. */
  51437. this.targetStopDuration = 0;
  51438. /**
  51439. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  51440. */
  51441. this.disposeOnStop = false;
  51442. /**
  51443. * Minimum power of emitting particles.
  51444. */
  51445. this.minEmitPower = 1;
  51446. /**
  51447. * Maximum power of emitting particles.
  51448. */
  51449. this.maxEmitPower = 1;
  51450. /**
  51451. * Minimum life time of emitting particles.
  51452. */
  51453. this.minLifeTime = 1;
  51454. /**
  51455. * Maximum life time of emitting particles.
  51456. */
  51457. this.maxLifeTime = 1;
  51458. /**
  51459. * Minimum Size of emitting particles.
  51460. */
  51461. this.minSize = 1;
  51462. /**
  51463. * Maximum Size of emitting particles.
  51464. */
  51465. this.maxSize = 1;
  51466. /**
  51467. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  51468. */
  51469. this.minAngularSpeed = 0;
  51470. /**
  51471. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  51472. */
  51473. this.maxAngularSpeed = 0;
  51474. /**
  51475. * The layer mask we are rendering the particles through.
  51476. */
  51477. this.layerMask = 0x0FFFFFFF;
  51478. /**
  51479. * This can help using your own shader to render the particle system.
  51480. * The according effect will be created
  51481. */
  51482. this.customShader = null;
  51483. /**
  51484. * By default particle system starts as soon as they are created. This prevents the
  51485. * automatic start to happen and let you decide when to start emitting particles.
  51486. */
  51487. this.preventAutoStart = false;
  51488. /**
  51489. * Callback triggered when the particle animation is ending.
  51490. */
  51491. this.onAnimationEnd = null;
  51492. /**
  51493. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  51494. */
  51495. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  51496. /**
  51497. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  51498. * to override the particles.
  51499. */
  51500. this.forceDepthWrite = false;
  51501. /**
  51502. * You can use gravity if you want to give an orientation to your particles.
  51503. */
  51504. this.gravity = BABYLON.Vector3.Zero();
  51505. /**
  51506. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  51507. */
  51508. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51509. /**
  51510. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  51511. */
  51512. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51513. /**
  51514. * Color the particle will have at the end of its lifetime.
  51515. */
  51516. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  51517. /**
  51518. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  51519. */
  51520. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  51521. /**
  51522. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  51523. */
  51524. this.spriteCellLoop = true;
  51525. /**
  51526. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  51527. */
  51528. this.spriteCellChangeSpeed = 0;
  51529. /**
  51530. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  51531. */
  51532. this.startSpriteCellID = 0;
  51533. /**
  51534. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  51535. */
  51536. this.endSpriteCellID = 0;
  51537. /**
  51538. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  51539. */
  51540. this.spriteCellWidth = 0;
  51541. /**
  51542. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  51543. */
  51544. this.spriteCellHeight = 0;
  51545. /**
  51546. * An event triggered when the system is disposed.
  51547. */
  51548. this.onDisposeObservable = new BABYLON.Observable();
  51549. this._particles = new Array();
  51550. this._stockParticles = new Array();
  51551. this._newPartsExcess = 0;
  51552. this._vertexBuffers = {};
  51553. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  51554. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  51555. this._scaledDirection = BABYLON.Vector3.Zero();
  51556. this._scaledGravity = BABYLON.Vector3.Zero();
  51557. this._currentRenderId = -1;
  51558. this._started = false;
  51559. this._stopped = false;
  51560. this._actualFrame = 0;
  51561. this._vertexBufferSize = 11;
  51562. // start of sub system methods
  51563. /**
  51564. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  51565. * Its lifetime will start back at 0.
  51566. */
  51567. this.recycleParticle = function (particle) {
  51568. var lastParticle = _this._particles.pop();
  51569. if (lastParticle !== particle) {
  51570. lastParticle.copyTo(particle);
  51571. }
  51572. _this._stockParticles.push(lastParticle);
  51573. };
  51574. this._createParticle = function () {
  51575. var particle;
  51576. if (_this._stockParticles.length !== 0) {
  51577. particle = _this._stockParticles.pop();
  51578. particle.age = 0;
  51579. particle.cellIndex = _this.startSpriteCellID;
  51580. }
  51581. else {
  51582. particle = new BABYLON.Particle(_this);
  51583. }
  51584. return particle;
  51585. };
  51586. this._emitFromParticle = function (particle) {
  51587. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  51588. return;
  51589. }
  51590. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  51591. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  51592. subSystem._rootParticleSystem = _this;
  51593. _this.activeSubSystems.push(subSystem);
  51594. subSystem.start();
  51595. };
  51596. this._appendParticleVertexes = null;
  51597. this.id = name;
  51598. this.name = name;
  51599. this._capacity = capacity;
  51600. this._epsilon = epsilon;
  51601. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  51602. if (isAnimationSheetEnabled) {
  51603. this._vertexBufferSize = 12;
  51604. }
  51605. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51606. this._customEffect = customEffect;
  51607. scene.particleSystems.push(this);
  51608. this._createIndexBuffer();
  51609. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  51610. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  51611. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  51612. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  51613. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  51614. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  51615. if (this._isAnimationSheetEnabled) {
  51616. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  51617. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  51618. }
  51619. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  51620. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  51621. this._vertexBuffers["options"] = options;
  51622. // Default emitter type
  51623. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  51624. this.updateFunction = function (particles) {
  51625. for (var index = 0; index < particles.length; index++) {
  51626. var particle = particles[index];
  51627. particle.age += _this._scaledUpdateSpeed;
  51628. if (particle.age >= particle.lifeTime) {
  51629. _this._emitFromParticle(particle);
  51630. _this.recycleParticle(particle);
  51631. index--;
  51632. continue;
  51633. }
  51634. else {
  51635. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  51636. particle.color.addInPlace(_this._scaledColorStep);
  51637. if (particle.color.a < 0)
  51638. particle.color.a = 0;
  51639. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  51640. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  51641. particle.position.addInPlace(_this._scaledDirection);
  51642. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  51643. particle.direction.addInPlace(_this._scaledGravity);
  51644. if (_this._isAnimationSheetEnabled) {
  51645. particle.updateCellIndex(_this._scaledUpdateSpeed);
  51646. }
  51647. }
  51648. }
  51649. };
  51650. }
  51651. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  51652. /**
  51653. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51654. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51655. */
  51656. get: function () {
  51657. if (this.particleEmitterType.direction1) {
  51658. return this.particleEmitterType.direction1;
  51659. }
  51660. return BABYLON.Vector3.Zero();
  51661. },
  51662. set: function (value) {
  51663. if (this.particleEmitterType.direction1) {
  51664. this.particleEmitterType.direction1 = value;
  51665. }
  51666. },
  51667. enumerable: true,
  51668. configurable: true
  51669. });
  51670. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  51671. /**
  51672. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  51673. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51674. */
  51675. get: function () {
  51676. if (this.particleEmitterType.direction2) {
  51677. return this.particleEmitterType.direction2;
  51678. }
  51679. return BABYLON.Vector3.Zero();
  51680. },
  51681. set: function (value) {
  51682. if (this.particleEmitterType.direction2) {
  51683. this.particleEmitterType.direction2 = value;
  51684. }
  51685. },
  51686. enumerable: true,
  51687. configurable: true
  51688. });
  51689. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  51690. /**
  51691. * 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.
  51692. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51693. */
  51694. get: function () {
  51695. if (this.particleEmitterType.minEmitBox) {
  51696. return this.particleEmitterType.minEmitBox;
  51697. }
  51698. return BABYLON.Vector3.Zero();
  51699. },
  51700. set: function (value) {
  51701. if (this.particleEmitterType.minEmitBox) {
  51702. this.particleEmitterType.minEmitBox = value;
  51703. }
  51704. },
  51705. enumerable: true,
  51706. configurable: true
  51707. });
  51708. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  51709. /**
  51710. * 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.
  51711. * This only works when particleEmitterTyps is a BoxParticleEmitter
  51712. */
  51713. get: function () {
  51714. if (this.particleEmitterType.maxEmitBox) {
  51715. return this.particleEmitterType.maxEmitBox;
  51716. }
  51717. return BABYLON.Vector3.Zero();
  51718. },
  51719. set: function (value) {
  51720. if (this.particleEmitterType.maxEmitBox) {
  51721. this.particleEmitterType.maxEmitBox = value;
  51722. }
  51723. },
  51724. enumerable: true,
  51725. configurable: true
  51726. });
  51727. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  51728. /**
  51729. * Sets a callback that will be triggered when the system is disposed.
  51730. */
  51731. set: function (callback) {
  51732. if (this._onDisposeObserver) {
  51733. this.onDisposeObservable.remove(this._onDisposeObserver);
  51734. }
  51735. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  51736. },
  51737. enumerable: true,
  51738. configurable: true
  51739. });
  51740. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  51741. /**
  51742. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  51743. */
  51744. get: function () {
  51745. return this._isAnimationSheetEnabled;
  51746. },
  51747. enumerable: true,
  51748. configurable: true
  51749. });
  51750. Object.defineProperty(ParticleSystem.prototype, "particles", {
  51751. //end of Sub-emitter
  51752. /**
  51753. * Gets the current list of active particles
  51754. */
  51755. get: function () {
  51756. return this._particles;
  51757. },
  51758. enumerable: true,
  51759. configurable: true
  51760. });
  51761. /**
  51762. * Returns the string "ParticleSystem"
  51763. * @returns a string containing the class name
  51764. */
  51765. ParticleSystem.prototype.getClassName = function () {
  51766. return "ParticleSystem";
  51767. };
  51768. ParticleSystem.prototype._createIndexBuffer = function () {
  51769. var indices = [];
  51770. var index = 0;
  51771. for (var count = 0; count < this._capacity; count++) {
  51772. indices.push(index);
  51773. indices.push(index + 1);
  51774. indices.push(index + 2);
  51775. indices.push(index);
  51776. indices.push(index + 2);
  51777. indices.push(index + 3);
  51778. index += 4;
  51779. }
  51780. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  51781. };
  51782. /**
  51783. * Gets the maximum number of particles active at the same time.
  51784. * @returns The max number of active particles.
  51785. */
  51786. ParticleSystem.prototype.getCapacity = function () {
  51787. return this._capacity;
  51788. };
  51789. /**
  51790. * Gets Wether there are still active particles in the system.
  51791. * @returns True if it is alive, otherwise false.
  51792. */
  51793. ParticleSystem.prototype.isAlive = function () {
  51794. return this._alive;
  51795. };
  51796. /**
  51797. * Gets Wether the system has been started.
  51798. * @returns True if it has been started, otherwise false.
  51799. */
  51800. ParticleSystem.prototype.isStarted = function () {
  51801. return this._started;
  51802. };
  51803. /**
  51804. * Starts the particle system and begins to emit.
  51805. */
  51806. ParticleSystem.prototype.start = function () {
  51807. this._started = true;
  51808. this._stopped = false;
  51809. this._actualFrame = 0;
  51810. if (this.subEmitters && this.subEmitters.length != 0) {
  51811. this.activeSubSystems = new Array();
  51812. }
  51813. };
  51814. /**
  51815. * Stops the particle system.
  51816. * @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.
  51817. */
  51818. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  51819. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  51820. this._stopped = true;
  51821. if (stopSubEmitters) {
  51822. this._stopSubEmitters();
  51823. }
  51824. };
  51825. // animation sheet
  51826. /**
  51827. * Remove all active particles
  51828. */
  51829. ParticleSystem.prototype.reset = function () {
  51830. this._stockParticles = [];
  51831. this._particles = [];
  51832. };
  51833. /**
  51834. * @ignore (for internal use only)
  51835. */
  51836. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  51837. var offset = index * this._vertexBufferSize;
  51838. this._vertexData[offset] = particle.position.x;
  51839. this._vertexData[offset + 1] = particle.position.y;
  51840. this._vertexData[offset + 2] = particle.position.z;
  51841. this._vertexData[offset + 3] = particle.color.r;
  51842. this._vertexData[offset + 4] = particle.color.g;
  51843. this._vertexData[offset + 5] = particle.color.b;
  51844. this._vertexData[offset + 6] = particle.color.a;
  51845. this._vertexData[offset + 7] = particle.angle;
  51846. this._vertexData[offset + 8] = particle.size;
  51847. this._vertexData[offset + 9] = offsetX;
  51848. this._vertexData[offset + 10] = offsetY;
  51849. };
  51850. /**
  51851. * @ignore (for internal use only)
  51852. */
  51853. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  51854. if (offsetX === 0)
  51855. offsetX = this._epsilon;
  51856. else if (offsetX === 1)
  51857. offsetX = 1 - this._epsilon;
  51858. if (offsetY === 0)
  51859. offsetY = this._epsilon;
  51860. else if (offsetY === 1)
  51861. offsetY = 1 - this._epsilon;
  51862. var offset = index * this._vertexBufferSize;
  51863. this._vertexData[offset] = particle.position.x;
  51864. this._vertexData[offset + 1] = particle.position.y;
  51865. this._vertexData[offset + 2] = particle.position.z;
  51866. this._vertexData[offset + 3] = particle.color.r;
  51867. this._vertexData[offset + 4] = particle.color.g;
  51868. this._vertexData[offset + 5] = particle.color.b;
  51869. this._vertexData[offset + 6] = particle.color.a;
  51870. this._vertexData[offset + 7] = particle.angle;
  51871. this._vertexData[offset + 8] = particle.size;
  51872. this._vertexData[offset + 9] = offsetX;
  51873. this._vertexData[offset + 10] = offsetY;
  51874. this._vertexData[offset + 11] = particle.cellIndex;
  51875. };
  51876. ParticleSystem.prototype._stopSubEmitters = function () {
  51877. if (!this.activeSubSystems) {
  51878. return;
  51879. }
  51880. this.activeSubSystems.forEach(function (subSystem) {
  51881. subSystem.stop(true);
  51882. });
  51883. this.activeSubSystems = new Array();
  51884. };
  51885. ParticleSystem.prototype._removeFromRoot = function () {
  51886. if (!this._rootParticleSystem) {
  51887. return;
  51888. }
  51889. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  51890. if (index !== -1) {
  51891. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  51892. }
  51893. };
  51894. // end of sub system methods
  51895. ParticleSystem.prototype._update = function (newParticles) {
  51896. // Update current
  51897. this._alive = this._particles.length > 0;
  51898. this.updateFunction(this._particles);
  51899. // Add new ones
  51900. var worldMatrix;
  51901. if (this.emitter.position) {
  51902. var emitterMesh = this.emitter;
  51903. worldMatrix = emitterMesh.getWorldMatrix();
  51904. }
  51905. else {
  51906. var emitterPosition = this.emitter;
  51907. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  51908. }
  51909. var particle;
  51910. for (var index = 0; index < newParticles; index++) {
  51911. if (this._particles.length === this._capacity) {
  51912. break;
  51913. }
  51914. particle = this._createParticle();
  51915. this._particles.push(particle);
  51916. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  51917. if (this.startPositionFunction) {
  51918. this.startPositionFunction(worldMatrix, particle.position, particle);
  51919. }
  51920. else {
  51921. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  51922. }
  51923. if (this.startDirectionFunction) {
  51924. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  51925. }
  51926. else {
  51927. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  51928. }
  51929. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  51930. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  51931. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  51932. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  51933. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  51934. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  51935. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  51936. }
  51937. };
  51938. ParticleSystem.prototype._getEffect = function () {
  51939. if (this._customEffect) {
  51940. return this._customEffect;
  51941. }
  51942. ;
  51943. var defines = [];
  51944. if (this._scene.clipPlane) {
  51945. defines.push("#define CLIPPLANE");
  51946. }
  51947. if (this._isAnimationSheetEnabled) {
  51948. defines.push("#define ANIMATESHEET");
  51949. }
  51950. // Effect
  51951. var join = defines.join("\n");
  51952. if (this._cachedDefines !== join) {
  51953. this._cachedDefines = join;
  51954. var attributesNamesOrOptions;
  51955. var effectCreationOption;
  51956. if (this._isAnimationSheetEnabled) {
  51957. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  51958. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  51959. }
  51960. else {
  51961. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  51962. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  51963. }
  51964. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  51965. }
  51966. return this._effect;
  51967. };
  51968. /**
  51969. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  51970. */
  51971. ParticleSystem.prototype.animate = function () {
  51972. if (!this._started)
  51973. return;
  51974. var effect = this._getEffect();
  51975. // Check
  51976. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  51977. return;
  51978. if (this._currentRenderId === this._scene.getRenderId()) {
  51979. return;
  51980. }
  51981. this._currentRenderId = this._scene.getRenderId();
  51982. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  51983. // determine the number of particles we need to create
  51984. var newParticles;
  51985. if (this.manualEmitCount > -1) {
  51986. newParticles = this.manualEmitCount;
  51987. this._newPartsExcess = 0;
  51988. this.manualEmitCount = 0;
  51989. }
  51990. else {
  51991. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  51992. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  51993. }
  51994. if (this._newPartsExcess > 1.0) {
  51995. newParticles += this._newPartsExcess >> 0;
  51996. this._newPartsExcess -= this._newPartsExcess >> 0;
  51997. }
  51998. this._alive = false;
  51999. if (!this._stopped) {
  52000. this._actualFrame += this._scaledUpdateSpeed;
  52001. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  52002. this.stop();
  52003. }
  52004. else {
  52005. newParticles = 0;
  52006. }
  52007. this._update(newParticles);
  52008. // Stopped?
  52009. if (this._stopped) {
  52010. if (!this._alive) {
  52011. this._started = false;
  52012. if (this.onAnimationEnd) {
  52013. this.onAnimationEnd();
  52014. }
  52015. if (this.disposeOnStop) {
  52016. this._scene._toBeDisposed.push(this);
  52017. }
  52018. }
  52019. }
  52020. // Animation sheet
  52021. if (this._isAnimationSheetEnabled) {
  52022. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  52023. }
  52024. else {
  52025. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  52026. }
  52027. // Update VBO
  52028. var offset = 0;
  52029. for (var index = 0; index < this._particles.length; index++) {
  52030. var particle = this._particles[index];
  52031. this._appendParticleVertexes(offset, particle);
  52032. offset += 4;
  52033. }
  52034. if (this._vertexBuffer) {
  52035. this._vertexBuffer.update(this._vertexData);
  52036. }
  52037. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  52038. this.stop();
  52039. }
  52040. };
  52041. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  52042. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  52043. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  52044. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  52045. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  52046. };
  52047. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  52048. this._appendParticleVertex(offset++, particle, 0, 0);
  52049. this._appendParticleVertex(offset++, particle, 1, 0);
  52050. this._appendParticleVertex(offset++, particle, 1, 1);
  52051. this._appendParticleVertex(offset++, particle, 0, 1);
  52052. };
  52053. /**
  52054. * Rebuilds the particle system.
  52055. */
  52056. ParticleSystem.prototype.rebuild = function () {
  52057. this._createIndexBuffer();
  52058. if (this._vertexBuffer) {
  52059. this._vertexBuffer._rebuild();
  52060. }
  52061. };
  52062. /**
  52063. * Is this system ready to be used/rendered
  52064. * @return true if the system is ready
  52065. */
  52066. ParticleSystem.prototype.isReady = function () {
  52067. var effect = this._getEffect();
  52068. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  52069. return false;
  52070. }
  52071. return true;
  52072. };
  52073. /**
  52074. * Renders the particle system in its current state.
  52075. * @returns the current number of particles
  52076. */
  52077. ParticleSystem.prototype.render = function () {
  52078. var effect = this._getEffect();
  52079. // Check
  52080. if (!this.isReady() || !this._particles.length) {
  52081. return 0;
  52082. }
  52083. var engine = this._scene.getEngine();
  52084. // Render
  52085. engine.enableEffect(effect);
  52086. engine.setState(false);
  52087. var viewMatrix = this._scene.getViewMatrix();
  52088. effect.setTexture("diffuseSampler", this.particleTexture);
  52089. effect.setMatrix("view", viewMatrix);
  52090. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  52091. if (this._isAnimationSheetEnabled && this.particleTexture) {
  52092. var baseSize = this.particleTexture.getBaseSize();
  52093. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  52094. }
  52095. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  52096. if (this._scene.clipPlane) {
  52097. var clipPlane = this._scene.clipPlane;
  52098. var invView = viewMatrix.clone();
  52099. invView.invert();
  52100. effect.setMatrix("invView", invView);
  52101. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  52102. }
  52103. // VBOs
  52104. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  52105. // Draw order
  52106. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  52107. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  52108. }
  52109. else {
  52110. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  52111. }
  52112. if (this.forceDepthWrite) {
  52113. engine.setDepthWrite(true);
  52114. }
  52115. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  52116. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  52117. return this._particles.length;
  52118. };
  52119. /**
  52120. * Disposes the particle system and free the associated resources
  52121. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  52122. */
  52123. ParticleSystem.prototype.dispose = function (disposeTexture) {
  52124. if (disposeTexture === void 0) { disposeTexture = true; }
  52125. if (this._vertexBuffer) {
  52126. this._vertexBuffer.dispose();
  52127. this._vertexBuffer = null;
  52128. }
  52129. if (this._indexBuffer) {
  52130. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  52131. this._indexBuffer = null;
  52132. }
  52133. if (disposeTexture && this.particleTexture) {
  52134. this.particleTexture.dispose();
  52135. this.particleTexture = null;
  52136. }
  52137. this._removeFromRoot();
  52138. // Remove from scene
  52139. var index = this._scene.particleSystems.indexOf(this);
  52140. if (index > -1) {
  52141. this._scene.particleSystems.splice(index, 1);
  52142. }
  52143. // Callback
  52144. this.onDisposeObservable.notifyObservers(this);
  52145. this.onDisposeObservable.clear();
  52146. };
  52147. /**
  52148. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  52149. * @param radius The radius of the sphere to emit from
  52150. * @returns the emitter
  52151. */
  52152. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  52153. if (radius === void 0) { radius = 1; }
  52154. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  52155. this.particleEmitterType = particleEmitter;
  52156. return particleEmitter;
  52157. };
  52158. /**
  52159. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  52160. * @param radius The radius of the sphere to emit from
  52161. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  52162. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  52163. * @returns the emitter
  52164. */
  52165. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  52166. if (radius === void 0) { radius = 1; }
  52167. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  52168. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  52169. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  52170. this.particleEmitterType = particleEmitter;
  52171. return particleEmitter;
  52172. };
  52173. /**
  52174. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  52175. * @param radius The radius of the cone to emit from
  52176. * @param angle The base angle of the cone
  52177. * @returns the emitter
  52178. */
  52179. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  52180. if (radius === void 0) { radius = 1; }
  52181. if (angle === void 0) { angle = Math.PI / 4; }
  52182. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  52183. this.particleEmitterType = particleEmitter;
  52184. return particleEmitter;
  52185. };
  52186. // 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.
  52187. /**
  52188. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  52189. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  52190. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  52191. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  52192. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  52193. * @returns the emitter
  52194. */
  52195. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  52196. var particleEmitter = new BABYLON.BoxParticleEmitter();
  52197. this.direction1 = direction1;
  52198. this.direction2 = direction2;
  52199. this.minEmitBox = minEmitBox;
  52200. this.maxEmitBox = maxEmitBox;
  52201. this.particleEmitterType = particleEmitter;
  52202. return particleEmitter;
  52203. };
  52204. // Clone
  52205. /**
  52206. * Clones the particle system.
  52207. * @param name The name of the cloned object
  52208. * @param newEmitter The new emitter to use
  52209. * @returns the cloned particle system
  52210. */
  52211. ParticleSystem.prototype.clone = function (name, newEmitter) {
  52212. var custom = null;
  52213. var program = null;
  52214. if (this.customShader != null) {
  52215. program = this.customShader;
  52216. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  52217. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  52218. }
  52219. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  52220. result.customShader = program;
  52221. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  52222. if (newEmitter === undefined) {
  52223. newEmitter = this.emitter;
  52224. }
  52225. result.emitter = newEmitter;
  52226. if (this.particleTexture) {
  52227. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  52228. }
  52229. if (!this.preventAutoStart) {
  52230. result.start();
  52231. }
  52232. return result;
  52233. };
  52234. /**
  52235. * Serializes the particle system to a JSON object.
  52236. * @returns the JSON object
  52237. */
  52238. ParticleSystem.prototype.serialize = function () {
  52239. var serializationObject = {};
  52240. serializationObject.name = this.name;
  52241. serializationObject.id = this.id;
  52242. // Emitter
  52243. if (this.emitter.position) {
  52244. var emitterMesh = this.emitter;
  52245. serializationObject.emitterId = emitterMesh.id;
  52246. }
  52247. else {
  52248. var emitterPosition = this.emitter;
  52249. serializationObject.emitter = emitterPosition.asArray();
  52250. }
  52251. serializationObject.capacity = this.getCapacity();
  52252. if (this.particleTexture) {
  52253. serializationObject.textureName = this.particleTexture.name;
  52254. }
  52255. // Animations
  52256. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  52257. // Particle system
  52258. serializationObject.minAngularSpeed = this.minAngularSpeed;
  52259. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  52260. serializationObject.minSize = this.minSize;
  52261. serializationObject.maxSize = this.maxSize;
  52262. serializationObject.minEmitPower = this.minEmitPower;
  52263. serializationObject.maxEmitPower = this.maxEmitPower;
  52264. serializationObject.minLifeTime = this.minLifeTime;
  52265. serializationObject.maxLifeTime = this.maxLifeTime;
  52266. serializationObject.emitRate = this.emitRate;
  52267. serializationObject.minEmitBox = this.minEmitBox.asArray();
  52268. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  52269. serializationObject.gravity = this.gravity.asArray();
  52270. serializationObject.direction1 = this.direction1.asArray();
  52271. serializationObject.direction2 = this.direction2.asArray();
  52272. serializationObject.color1 = this.color1.asArray();
  52273. serializationObject.color2 = this.color2.asArray();
  52274. serializationObject.colorDead = this.colorDead.asArray();
  52275. serializationObject.updateSpeed = this.updateSpeed;
  52276. serializationObject.targetStopDuration = this.targetStopDuration;
  52277. serializationObject.textureMask = this.textureMask.asArray();
  52278. serializationObject.blendMode = this.blendMode;
  52279. serializationObject.customShader = this.customShader;
  52280. serializationObject.preventAutoStart = this.preventAutoStart;
  52281. serializationObject.startSpriteCellID = this.startSpriteCellID;
  52282. serializationObject.endSpriteCellID = this.endSpriteCellID;
  52283. serializationObject.spriteCellLoop = this.spriteCellLoop;
  52284. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  52285. serializationObject.spriteCellWidth = this.spriteCellWidth;
  52286. serializationObject.spriteCellHeight = this.spriteCellHeight;
  52287. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  52288. // Emitter
  52289. if (this.particleEmitterType) {
  52290. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  52291. }
  52292. return serializationObject;
  52293. };
  52294. /**
  52295. * Parses a JSON object to create a particle system.
  52296. * @param parsedParticleSystem The JSON object to parse
  52297. * @param scene The scene to create the particle system in
  52298. * @param rootUrl The root url to use to load external dependencies like texture
  52299. * @returns the Parsed particle system
  52300. */
  52301. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  52302. var name = parsedParticleSystem.name;
  52303. var custom = null;
  52304. var program = null;
  52305. if (parsedParticleSystem.customShader) {
  52306. program = parsedParticleSystem.customShader;
  52307. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  52308. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  52309. }
  52310. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  52311. particleSystem.customShader = program;
  52312. if (parsedParticleSystem.id) {
  52313. particleSystem.id = parsedParticleSystem.id;
  52314. }
  52315. // Auto start
  52316. if (parsedParticleSystem.preventAutoStart) {
  52317. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  52318. }
  52319. // Texture
  52320. if (parsedParticleSystem.textureName) {
  52321. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  52322. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  52323. }
  52324. // Emitter
  52325. if (parsedParticleSystem.emitterId) {
  52326. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  52327. }
  52328. else {
  52329. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  52330. }
  52331. // Animations
  52332. if (parsedParticleSystem.animations) {
  52333. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  52334. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  52335. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  52336. }
  52337. }
  52338. if (parsedParticleSystem.autoAnimate) {
  52339. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  52340. }
  52341. // Particle system
  52342. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  52343. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  52344. particleSystem.minSize = parsedParticleSystem.minSize;
  52345. particleSystem.maxSize = parsedParticleSystem.maxSize;
  52346. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  52347. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  52348. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  52349. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  52350. particleSystem.emitRate = parsedParticleSystem.emitRate;
  52351. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  52352. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  52353. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  52354. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  52355. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  52356. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  52357. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  52358. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  52359. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  52360. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  52361. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  52362. particleSystem.blendMode = parsedParticleSystem.blendMode;
  52363. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  52364. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  52365. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  52366. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  52367. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  52368. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  52369. if (!particleSystem.preventAutoStart) {
  52370. particleSystem.start();
  52371. }
  52372. return particleSystem;
  52373. };
  52374. /**
  52375. * Source color is added to the destination color without alpha affecting the result.
  52376. */
  52377. ParticleSystem.BLENDMODE_ONEONE = 0;
  52378. /**
  52379. * Blend current color and particle color using particle’s alpha.
  52380. */
  52381. ParticleSystem.BLENDMODE_STANDARD = 1;
  52382. return ParticleSystem;
  52383. }());
  52384. BABYLON.ParticleSystem = ParticleSystem;
  52385. })(BABYLON || (BABYLON = {}));
  52386. //# sourceMappingURL=babylon.particleSystem.js.map
  52387. "use strict";
  52388. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  52389. "use strict";
  52390. var BABYLON;
  52391. (function (BABYLON) {
  52392. /**
  52393. * Particle emitter emitting particles from the inside of a box.
  52394. * It emits the particles randomly between 2 given directions.
  52395. */
  52396. var BoxParticleEmitter = /** @class */ (function () {
  52397. /**
  52398. * Creates a new instance of @see BoxParticleEmitter
  52399. */
  52400. function BoxParticleEmitter() {
  52401. /**
  52402. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52403. */
  52404. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  52405. /**
  52406. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  52407. */
  52408. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  52409. /**
  52410. * 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.
  52411. */
  52412. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  52413. /**
  52414. * 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.
  52415. */
  52416. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  52417. }
  52418. /**
  52419. * Called by the particle System when the direction is computed for the created particle.
  52420. * @param emitPower is the power of the particle (speed)
  52421. * @param worldMatrix is the world matrix of the particle system
  52422. * @param directionToUpdate is the direction vector to update with the result
  52423. * @param particle is the particle we are computed the direction for
  52424. */
  52425. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52426. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  52427. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  52428. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  52429. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  52430. };
  52431. /**
  52432. * Called by the particle System when the position is computed for the created particle.
  52433. * @param worldMatrix is the world matrix of the particle system
  52434. * @param positionToUpdate is the position vector to update with the result
  52435. * @param particle is the particle we are computed the position for
  52436. */
  52437. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52438. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  52439. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  52440. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  52441. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52442. };
  52443. /**
  52444. * Clones the current emitter and returns a copy of it
  52445. * @returns the new emitter
  52446. */
  52447. BoxParticleEmitter.prototype.clone = function () {
  52448. var newOne = new BoxParticleEmitter();
  52449. BABYLON.Tools.DeepCopy(this, newOne);
  52450. return newOne;
  52451. };
  52452. /**
  52453. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52454. * @param effect defines the update shader
  52455. */
  52456. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  52457. effect.setVector3("direction1", this.direction1);
  52458. effect.setVector3("direction2", this.direction2);
  52459. effect.setVector3("minEmitBox", this.minEmitBox);
  52460. effect.setVector3("maxEmitBox", this.maxEmitBox);
  52461. };
  52462. /**
  52463. * Returns a string to use to update the GPU particles update shader
  52464. * @returns a string containng the defines string
  52465. */
  52466. BoxParticleEmitter.prototype.getEffectDefines = function () {
  52467. return "#define BOXEMITTER";
  52468. };
  52469. /**
  52470. * Returns the string "BoxEmitter"
  52471. * @returns a string containing the class name
  52472. */
  52473. BoxParticleEmitter.prototype.getClassName = function () {
  52474. return "BoxEmitter";
  52475. };
  52476. /**
  52477. * Serializes the particle system to a JSON object.
  52478. * @returns the JSON object
  52479. */
  52480. BoxParticleEmitter.prototype.serialize = function () {
  52481. var serializationObject = {};
  52482. serializationObject.type = this.getClassName();
  52483. serializationObject.direction1 = this.direction1.asArray();
  52484. ;
  52485. serializationObject.direction2 = this.direction2.asArray();
  52486. ;
  52487. serializationObject.minEmitBox = this.minEmitBox.asArray();
  52488. ;
  52489. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  52490. ;
  52491. return serializationObject;
  52492. };
  52493. /**
  52494. * Parse properties from a JSON object
  52495. * @param serializationObject defines the JSON object
  52496. */
  52497. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  52498. this.direction1.copyFrom(serializationObject.direction1);
  52499. this.direction2.copyFrom(serializationObject.direction2);
  52500. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  52501. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  52502. };
  52503. return BoxParticleEmitter;
  52504. }());
  52505. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  52506. })(BABYLON || (BABYLON = {}));
  52507. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  52508. "use strict";
  52509. var BABYLON;
  52510. (function (BABYLON) {
  52511. /**
  52512. * Particle emitter emitting particles from the inside of a cone.
  52513. * It emits the particles alongside the cone volume from the base to the particle.
  52514. * The emission direction might be randomized.
  52515. */
  52516. var ConeParticleEmitter = /** @class */ (function () {
  52517. /**
  52518. * Creates a new instance of @see ConeParticleEmitter
  52519. * @param radius the radius of the emission cone (1 by default)
  52520. * @param angles the cone base angle (PI by default)
  52521. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  52522. */
  52523. function ConeParticleEmitter(radius,
  52524. /**
  52525. * The radius of the emission cone.
  52526. */
  52527. angle,
  52528. /**
  52529. * The cone base angle.
  52530. */
  52531. directionRandomizer) {
  52532. if (radius === void 0) { radius = 1; }
  52533. if (angle === void 0) { angle = Math.PI; }
  52534. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  52535. this.angle = angle;
  52536. this.directionRandomizer = directionRandomizer;
  52537. this.radius = radius;
  52538. }
  52539. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  52540. /**
  52541. * Gets the radius of the emission cone.
  52542. */
  52543. get: function () {
  52544. return this._radius;
  52545. },
  52546. /**
  52547. * Sets the radius of the emission cone.
  52548. */
  52549. set: function (value) {
  52550. this._radius = value;
  52551. if (this.angle !== 0) {
  52552. this._height = value / Math.tan(this.angle / 2);
  52553. }
  52554. else {
  52555. this._height = 1;
  52556. }
  52557. },
  52558. enumerable: true,
  52559. configurable: true
  52560. });
  52561. /**
  52562. * Called by the particle System when the direction is computed for the created particle.
  52563. * @param emitPower is the power of the particle (speed)
  52564. * @param worldMatrix is the world matrix of the particle system
  52565. * @param directionToUpdate is the direction vector to update with the result
  52566. * @param particle is the particle we are computed the direction for
  52567. */
  52568. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52569. if (this.angle === 0) {
  52570. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  52571. }
  52572. else {
  52573. // measure the direction Vector from the emitter to the particle.
  52574. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  52575. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52576. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52577. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52578. direction.x += randX;
  52579. direction.y += randY;
  52580. direction.z += randZ;
  52581. direction.normalize();
  52582. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  52583. }
  52584. };
  52585. /**
  52586. * Called by the particle System when the position is computed for the created particle.
  52587. * @param worldMatrix is the world matrix of the particle system
  52588. * @param positionToUpdate is the position vector to update with the result
  52589. * @param particle is the particle we are computed the position for
  52590. */
  52591. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52592. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  52593. var h = BABYLON.Scalar.RandomRange(0, 1);
  52594. // Better distribution in a cone at normal angles.
  52595. h = 1 - h * h;
  52596. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  52597. radius = radius * h / this._height;
  52598. var randX = radius * Math.sin(s);
  52599. var randZ = radius * Math.cos(s);
  52600. var randY = h * this._height;
  52601. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52602. };
  52603. /**
  52604. * Clones the current emitter and returns a copy of it
  52605. * @returns the new emitter
  52606. */
  52607. ConeParticleEmitter.prototype.clone = function () {
  52608. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  52609. BABYLON.Tools.DeepCopy(this, newOne);
  52610. return newOne;
  52611. };
  52612. /**
  52613. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52614. * @param effect defines the update shader
  52615. */
  52616. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  52617. effect.setFloat("radius", this.radius);
  52618. effect.setFloat("angle", this.angle);
  52619. effect.setFloat("height", this._height);
  52620. effect.setFloat("directionRandomizer", this.directionRandomizer);
  52621. };
  52622. /**
  52623. * Returns a string to use to update the GPU particles update shader
  52624. * @returns a string containng the defines string
  52625. */
  52626. ConeParticleEmitter.prototype.getEffectDefines = function () {
  52627. return "#define CONEEMITTER";
  52628. };
  52629. /**
  52630. * Returns the string "BoxEmitter"
  52631. * @returns a string containing the class name
  52632. */
  52633. ConeParticleEmitter.prototype.getClassName = function () {
  52634. return "ConeEmitter";
  52635. };
  52636. /**
  52637. * Serializes the particle system to a JSON object.
  52638. * @returns the JSON object
  52639. */
  52640. ConeParticleEmitter.prototype.serialize = function () {
  52641. var serializationObject = {};
  52642. serializationObject.type = this.getClassName();
  52643. serializationObject.radius = this.radius;
  52644. serializationObject.angle = this.angle;
  52645. serializationObject.directionRandomizer = this.directionRandomizer;
  52646. return serializationObject;
  52647. };
  52648. /**
  52649. * Parse properties from a JSON object
  52650. * @param serializationObject defines the JSON object
  52651. */
  52652. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  52653. this.radius = serializationObject.radius;
  52654. this.angle = serializationObject.angle;
  52655. this.directionRandomizer = serializationObject.directionRandomizer;
  52656. };
  52657. return ConeParticleEmitter;
  52658. }());
  52659. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  52660. })(BABYLON || (BABYLON = {}));
  52661. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  52662. "use strict";
  52663. var BABYLON;
  52664. (function (BABYLON) {
  52665. /**
  52666. * Particle emitter emitting particles from the inside of a sphere.
  52667. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  52668. */
  52669. var SphereParticleEmitter = /** @class */ (function () {
  52670. /**
  52671. * Creates a new instance of @see SphereParticleEmitter
  52672. * @param radius the radius of the emission sphere (1 by default)
  52673. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  52674. */
  52675. function SphereParticleEmitter(
  52676. /**
  52677. * The radius of the emission sphere.
  52678. */
  52679. radius,
  52680. /**
  52681. * How much to randomize the particle direction [0-1].
  52682. */
  52683. directionRandomizer) {
  52684. if (radius === void 0) { radius = 1; }
  52685. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  52686. this.radius = radius;
  52687. this.directionRandomizer = directionRandomizer;
  52688. }
  52689. /**
  52690. * Called by the particle System when the direction is computed for the created particle.
  52691. * @param emitPower is the power of the particle (speed)
  52692. * @param worldMatrix is the world matrix of the particle system
  52693. * @param directionToUpdate is the direction vector to update with the result
  52694. * @param particle is the particle we are computed the direction for
  52695. */
  52696. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52697. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  52698. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52699. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52700. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  52701. direction.x += randX;
  52702. direction.y += randY;
  52703. direction.z += randZ;
  52704. direction.normalize();
  52705. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  52706. };
  52707. /**
  52708. * Called by the particle System when the position is computed for the created particle.
  52709. * @param worldMatrix is the world matrix of the particle system
  52710. * @param positionToUpdate is the position vector to update with the result
  52711. * @param particle is the particle we are computed the position for
  52712. */
  52713. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  52714. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  52715. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  52716. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  52717. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  52718. var randY = randRadius * Math.cos(theta);
  52719. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  52720. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  52721. };
  52722. /**
  52723. * Clones the current emitter and returns a copy of it
  52724. * @returns the new emitter
  52725. */
  52726. SphereParticleEmitter.prototype.clone = function () {
  52727. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  52728. BABYLON.Tools.DeepCopy(this, newOne);
  52729. return newOne;
  52730. };
  52731. /**
  52732. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52733. * @param effect defines the update shader
  52734. */
  52735. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  52736. effect.setFloat("radius", this.radius);
  52737. effect.setFloat("directionRandomizer", this.directionRandomizer);
  52738. };
  52739. /**
  52740. * Returns a string to use to update the GPU particles update shader
  52741. * @returns a string containng the defines string
  52742. */
  52743. SphereParticleEmitter.prototype.getEffectDefines = function () {
  52744. return "#define SPHEREEMITTER";
  52745. };
  52746. /**
  52747. * Returns the string "SphereParticleEmitter"
  52748. * @returns a string containing the class name
  52749. */
  52750. SphereParticleEmitter.prototype.getClassName = function () {
  52751. return "SphereParticleEmitter";
  52752. };
  52753. /**
  52754. * Serializes the particle system to a JSON object.
  52755. * @returns the JSON object
  52756. */
  52757. SphereParticleEmitter.prototype.serialize = function () {
  52758. var serializationObject = {};
  52759. serializationObject.type = this.getClassName();
  52760. serializationObject.radius = this.radius;
  52761. serializationObject.directionRandomizer = this.directionRandomizer;
  52762. return serializationObject;
  52763. };
  52764. /**
  52765. * Parse properties from a JSON object
  52766. * @param serializationObject defines the JSON object
  52767. */
  52768. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  52769. this.radius = serializationObject.radius;
  52770. this.directionRandomizer = serializationObject.directionRandomizer;
  52771. };
  52772. return SphereParticleEmitter;
  52773. }());
  52774. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  52775. /**
  52776. * Particle emitter emitting particles from the inside of a sphere.
  52777. * It emits the particles randomly between two vectors.
  52778. */
  52779. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  52780. __extends(SphereDirectedParticleEmitter, _super);
  52781. /**
  52782. * Creates a new instance of @see SphereDirectedParticleEmitter
  52783. * @param radius the radius of the emission sphere (1 by default)
  52784. * @param direction1 the min limit of the emission direction (up vector by default)
  52785. * @param direction2 the max limit of the emission direction (up vector by default)
  52786. */
  52787. function SphereDirectedParticleEmitter(radius,
  52788. /**
  52789. * The min limit of the emission direction.
  52790. */
  52791. direction1,
  52792. /**
  52793. * The max limit of the emission direction.
  52794. */
  52795. direction2) {
  52796. if (radius === void 0) { radius = 1; }
  52797. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  52798. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  52799. var _this = _super.call(this, radius) || this;
  52800. _this.direction1 = direction1;
  52801. _this.direction2 = direction2;
  52802. return _this;
  52803. }
  52804. /**
  52805. * Called by the particle System when the direction is computed for the created particle.
  52806. * @param emitPower is the power of the particle (speed)
  52807. * @param worldMatrix is the world matrix of the particle system
  52808. * @param directionToUpdate is the direction vector to update with the result
  52809. * @param particle is the particle we are computed the direction for
  52810. */
  52811. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  52812. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  52813. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  52814. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  52815. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  52816. };
  52817. /**
  52818. * Clones the current emitter and returns a copy of it
  52819. * @returns the new emitter
  52820. */
  52821. SphereDirectedParticleEmitter.prototype.clone = function () {
  52822. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  52823. BABYLON.Tools.DeepCopy(this, newOne);
  52824. return newOne;
  52825. };
  52826. /**
  52827. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  52828. * @param effect defines the update shader
  52829. */
  52830. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  52831. effect.setFloat("radius", this.radius);
  52832. effect.setVector3("direction1", this.direction1);
  52833. effect.setVector3("direction2", this.direction2);
  52834. };
  52835. /**
  52836. * Returns a string to use to update the GPU particles update shader
  52837. * @returns a string containng the defines string
  52838. */
  52839. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  52840. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  52841. };
  52842. /**
  52843. * Returns the string "SphereDirectedParticleEmitter"
  52844. * @returns a string containing the class name
  52845. */
  52846. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  52847. return "SphereDirectedParticleEmitter";
  52848. };
  52849. /**
  52850. * Serializes the particle system to a JSON object.
  52851. * @returns the JSON object
  52852. */
  52853. SphereDirectedParticleEmitter.prototype.serialize = function () {
  52854. var serializationObject = _super.prototype.serialize.call(this);
  52855. ;
  52856. serializationObject.direction1 = this.direction1.asArray();
  52857. ;
  52858. serializationObject.direction2 = this.direction2.asArray();
  52859. ;
  52860. return serializationObject;
  52861. };
  52862. /**
  52863. * Parse properties from a JSON object
  52864. * @param serializationObject defines the JSON object
  52865. */
  52866. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  52867. _super.prototype.parse.call(this, serializationObject);
  52868. this.direction1.copyFrom(serializationObject.direction1);
  52869. this.direction2.copyFrom(serializationObject.direction2);
  52870. };
  52871. return SphereDirectedParticleEmitter;
  52872. }(SphereParticleEmitter));
  52873. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  52874. })(BABYLON || (BABYLON = {}));
  52875. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  52876. "use strict";
  52877. var __assign = (this && this.__assign) || Object.assign || function(t) {
  52878. for (var s, i = 1, n = arguments.length; i < n; i++) {
  52879. s = arguments[i];
  52880. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  52881. t[p] = s[p];
  52882. }
  52883. return t;
  52884. };
  52885. var BABYLON;
  52886. (function (BABYLON) {
  52887. /**
  52888. * This represents a GPU particle system in Babylon
  52889. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  52890. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  52891. */
  52892. var GPUParticleSystem = /** @class */ (function () {
  52893. /**
  52894. * Instantiates a GPU particle system.
  52895. * 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.
  52896. * @param name The name of the particle system
  52897. * @param capacity The max number of particles alive at the same time
  52898. * @param scene The scene the particle system belongs to
  52899. */
  52900. function GPUParticleSystem(name, options, scene) {
  52901. /**
  52902. * The emitter represents the Mesh or position we are attaching the particle system to.
  52903. */
  52904. this.emitter = null;
  52905. /**
  52906. * The rendering group used by the Particle system to chose when to render.
  52907. */
  52908. this.renderingGroupId = 0;
  52909. /**
  52910. * The layer mask we are rendering the particles through.
  52911. */
  52912. this.layerMask = 0x0FFFFFFF;
  52913. this._targetIndex = 0;
  52914. this._currentRenderId = -1;
  52915. this._started = false;
  52916. this._stopped = false;
  52917. this._timeDelta = 0;
  52918. this._attributesStrideSize = 14;
  52919. this._actualFrame = 0;
  52920. /**
  52921. * List of animations used by the particle system.
  52922. */
  52923. this.animations = [];
  52924. /**
  52925. * An event triggered when the system is disposed.
  52926. */
  52927. this.onDisposeObservable = new BABYLON.Observable();
  52928. /**
  52929. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  52930. */
  52931. this.updateSpeed = 0.01;
  52932. /**
  52933. * The amount of time the particle system is running (depends of the overall update speed).
  52934. */
  52935. this.targetStopDuration = 0;
  52936. /**
  52937. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  52938. */
  52939. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  52940. /**
  52941. * Minimum life time of emitting particles.
  52942. */
  52943. this.minLifeTime = 1;
  52944. /**
  52945. * Maximum life time of emitting particles.
  52946. */
  52947. this.maxLifeTime = 1;
  52948. /**
  52949. * Minimum Size of emitting particles.
  52950. */
  52951. this.minSize = 1;
  52952. /**
  52953. * Maximum Size of emitting particles.
  52954. */
  52955. this.maxSize = 1;
  52956. /**
  52957. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  52958. */
  52959. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  52960. /**
  52961. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  52962. */
  52963. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  52964. /**
  52965. * Color the particle will have at the end of its lifetime.
  52966. */
  52967. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  52968. /**
  52969. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  52970. */
  52971. this.emitRate = 100;
  52972. /**
  52973. * You can use gravity if you want to give an orientation to your particles.
  52974. */
  52975. this.gravity = BABYLON.Vector3.Zero();
  52976. /**
  52977. * Minimum power of emitting particles.
  52978. */
  52979. this.minEmitPower = 1;
  52980. /**
  52981. * Maximum power of emitting particles.
  52982. */
  52983. this.maxEmitPower = 1;
  52984. /**
  52985. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  52986. * to override the particles.
  52987. */
  52988. this.forceDepthWrite = false;
  52989. this.id = name;
  52990. this.name = name;
  52991. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52992. this._engine = this._scene.getEngine();
  52993. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  52994. this._capacity = fullOptions.capacity;
  52995. this._activeCount = fullOptions.capacity;
  52996. this._currentActiveCount = 0;
  52997. this._scene.particleSystems.push(this);
  52998. this._updateEffectOptions = {
  52999. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  53000. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  53001. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle", "stopFactor"],
  53002. uniformBuffersNames: [],
  53003. samplers: ["randomSampler"],
  53004. defines: "",
  53005. fallbacks: null,
  53006. onCompiled: null,
  53007. onError: null,
  53008. indexParameters: null,
  53009. maxSimultaneousLights: 0,
  53010. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  53011. };
  53012. // Random data
  53013. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  53014. var d = [];
  53015. for (var i = 0; i < maxTextureSize; ++i) {
  53016. d.push(Math.random());
  53017. d.push(Math.random());
  53018. d.push(Math.random());
  53019. d.push(Math.random());
  53020. }
  53021. 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);
  53022. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  53023. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  53024. this._randomTextureSize = maxTextureSize;
  53025. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  53026. }
  53027. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  53028. /**
  53029. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  53030. */
  53031. get: function () {
  53032. if (!BABYLON.Engine.LastCreatedEngine) {
  53033. return false;
  53034. }
  53035. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  53036. },
  53037. enumerable: true,
  53038. configurable: true
  53039. });
  53040. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  53041. /**
  53042. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  53043. * This only works when particleEmitterTyps is a BoxParticleEmitter
  53044. */
  53045. get: function () {
  53046. if (this.particleEmitterType.direction1) {
  53047. return this.particleEmitterType.direction1;
  53048. }
  53049. return BABYLON.Vector3.Zero();
  53050. },
  53051. set: function (value) {
  53052. if (this.particleEmitterType.direction1) {
  53053. this.particleEmitterType.direction1 = value;
  53054. }
  53055. },
  53056. enumerable: true,
  53057. configurable: true
  53058. });
  53059. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  53060. /**
  53061. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  53062. * This only works when particleEmitterTyps is a BoxParticleEmitter
  53063. */
  53064. get: function () {
  53065. if (this.particleEmitterType.direction2) {
  53066. return this.particleEmitterType.direction2;
  53067. }
  53068. return BABYLON.Vector3.Zero();
  53069. },
  53070. set: function (value) {
  53071. if (this.particleEmitterType.direction2) {
  53072. this.particleEmitterType.direction2 = value;
  53073. }
  53074. },
  53075. enumerable: true,
  53076. configurable: true
  53077. });
  53078. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  53079. /**
  53080. * 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.
  53081. * This only works when particleEmitterTyps is a BoxParticleEmitter
  53082. */
  53083. get: function () {
  53084. if (this.particleEmitterType.minEmitBox) {
  53085. return this.particleEmitterType.minEmitBox;
  53086. }
  53087. return BABYLON.Vector3.Zero();
  53088. },
  53089. set: function (value) {
  53090. if (this.particleEmitterType.minEmitBox) {
  53091. this.particleEmitterType.minEmitBox = value;
  53092. }
  53093. },
  53094. enumerable: true,
  53095. configurable: true
  53096. });
  53097. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  53098. /**
  53099. * 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.
  53100. * This only works when particleEmitterTyps is a BoxParticleEmitter
  53101. */
  53102. get: function () {
  53103. if (this.particleEmitterType.maxEmitBox) {
  53104. return this.particleEmitterType.maxEmitBox;
  53105. }
  53106. return BABYLON.Vector3.Zero();
  53107. },
  53108. set: function (value) {
  53109. if (this.particleEmitterType.maxEmitBox) {
  53110. this.particleEmitterType.maxEmitBox = value;
  53111. }
  53112. },
  53113. enumerable: true,
  53114. configurable: true
  53115. });
  53116. /**
  53117. * Gets the maximum number of particles active at the same time.
  53118. * @returns The max number of active particles.
  53119. */
  53120. GPUParticleSystem.prototype.getCapacity = function () {
  53121. return this._capacity;
  53122. };
  53123. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  53124. /**
  53125. * Gets or set the number of active particles
  53126. */
  53127. get: function () {
  53128. return this._activeCount;
  53129. },
  53130. set: function (value) {
  53131. this._activeCount = Math.min(value, this._capacity);
  53132. },
  53133. enumerable: true,
  53134. configurable: true
  53135. });
  53136. /**
  53137. * Is this system ready to be used/rendered
  53138. * @return true if the system is ready
  53139. */
  53140. GPUParticleSystem.prototype.isReady = function () {
  53141. if (!this.emitter || !this._updateEffect || !this._renderEffect ||
  53142. !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  53143. return false;
  53144. }
  53145. return true;
  53146. };
  53147. /**
  53148. * Gets Wether the system has been started.
  53149. * @returns True if it has been started, otherwise false.
  53150. */
  53151. GPUParticleSystem.prototype.isStarted = function () {
  53152. return this._started;
  53153. };
  53154. /**
  53155. * Starts the particle system and begins to emit.
  53156. */
  53157. GPUParticleSystem.prototype.start = function () {
  53158. this._started = true;
  53159. this._stopped = false;
  53160. };
  53161. /**
  53162. * Stops the particle system.
  53163. */
  53164. GPUParticleSystem.prototype.stop = function () {
  53165. this._stopped = true;
  53166. };
  53167. /**
  53168. * Remove all active particles
  53169. */
  53170. GPUParticleSystem.prototype.reset = function () {
  53171. this._releaseBuffers();
  53172. this._releaseVAOs();
  53173. this._currentActiveCount = 0;
  53174. this._targetIndex = 0;
  53175. };
  53176. /**
  53177. * Returns the string "GPUParticleSystem"
  53178. * @returns a string containing the class name
  53179. */
  53180. GPUParticleSystem.prototype.getClassName = function () {
  53181. return "GPUParticleSystem";
  53182. };
  53183. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  53184. var updateVertexBuffers = {};
  53185. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  53186. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  53187. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  53188. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  53189. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  53190. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  53191. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  53192. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  53193. this._engine.bindArrayBuffer(null);
  53194. return vao;
  53195. };
  53196. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  53197. var renderVertexBuffers = {};
  53198. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  53199. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  53200. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  53201. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  53202. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  53203. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  53204. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  53205. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  53206. this._engine.bindArrayBuffer(null);
  53207. return vao;
  53208. };
  53209. GPUParticleSystem.prototype._initialize = function (force) {
  53210. if (force === void 0) { force = false; }
  53211. if (this._buffer0 && !force) {
  53212. return;
  53213. }
  53214. var engine = this._scene.getEngine();
  53215. var data = new Array();
  53216. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  53217. // position
  53218. data.push(0.0);
  53219. data.push(0.0);
  53220. data.push(0.0);
  53221. // Age and life
  53222. data.push(0.0); // create the particle as a dead one to create a new one at start
  53223. data.push(0.0);
  53224. // Seed
  53225. data.push(Math.random());
  53226. // Size
  53227. data.push(0.0);
  53228. // color
  53229. data.push(0.0);
  53230. data.push(0.0);
  53231. data.push(0.0);
  53232. data.push(0.0);
  53233. // direction
  53234. data.push(0.0);
  53235. data.push(0.0);
  53236. data.push(0.0);
  53237. }
  53238. // Sprite data
  53239. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  53240. -0.5, 0.5, 0, 1,
  53241. -0.5, -0.5, 0, 0,
  53242. 0.5, -0.5, 1, 0]);
  53243. // Buffers
  53244. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  53245. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  53246. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  53247. // Update VAO
  53248. this._updateVAO = [];
  53249. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  53250. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  53251. // Render VAO
  53252. this._renderVAO = [];
  53253. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  53254. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  53255. // Links
  53256. this._sourceBuffer = this._buffer0;
  53257. this._targetBuffer = this._buffer1;
  53258. };
  53259. /** @ignore */
  53260. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  53261. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  53262. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  53263. return;
  53264. }
  53265. this._updateEffectOptions.defines = defines;
  53266. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  53267. };
  53268. /** @ignore */
  53269. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  53270. var defines = "";
  53271. if (this._scene.clipPlane) {
  53272. defines = "\n#define CLIPPLANE";
  53273. }
  53274. if (this._renderEffect && this._renderEffect.defines === defines) {
  53275. return;
  53276. }
  53277. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  53278. };
  53279. /**
  53280. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  53281. */
  53282. GPUParticleSystem.prototype.animate = function () {
  53283. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  53284. this._actualFrame += this._timeDelta;
  53285. if (!this._stopped) {
  53286. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  53287. this.stop();
  53288. }
  53289. }
  53290. };
  53291. /**
  53292. * Renders the particle system in its current state.
  53293. * @returns the current number of particles
  53294. */
  53295. GPUParticleSystem.prototype.render = function () {
  53296. if (!this._started) {
  53297. return 0;
  53298. }
  53299. this._recreateUpdateEffect();
  53300. this._recreateRenderEffect();
  53301. if (!this.isReady()) {
  53302. return 0;
  53303. }
  53304. if (this._currentRenderId === this._scene.getRenderId()) {
  53305. return 0;
  53306. }
  53307. this._currentRenderId = this._scene.getRenderId();
  53308. // Get everything ready to render
  53309. this._initialize();
  53310. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  53311. // Enable update effect
  53312. this._engine.enableEffect(this._updateEffect);
  53313. this._engine.setState(false);
  53314. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  53315. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  53316. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  53317. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  53318. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  53319. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  53320. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  53321. this._updateEffect.setDirectColor4("color1", this.color1);
  53322. this._updateEffect.setDirectColor4("color2", this.color2);
  53323. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  53324. this._updateEffect.setVector3("gravity", this.gravity);
  53325. if (this.particleEmitterType) {
  53326. this.particleEmitterType.applyToShader(this._updateEffect);
  53327. }
  53328. var emitterWM;
  53329. if (this.emitter.position) {
  53330. var emitterMesh = this.emitter;
  53331. emitterWM = emitterMesh.getWorldMatrix();
  53332. }
  53333. else {
  53334. var emitterPosition = this.emitter;
  53335. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  53336. }
  53337. this._updateEffect.setMatrix("emitterWM", emitterWM);
  53338. // Bind source VAO
  53339. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  53340. // Update
  53341. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  53342. this._engine.setRasterizerState(false);
  53343. this._engine.beginTransformFeedback();
  53344. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  53345. this._engine.endTransformFeedback();
  53346. this._engine.setRasterizerState(true);
  53347. this._engine.bindTransformFeedbackBuffer(null);
  53348. // Enable render effect
  53349. this._engine.enableEffect(this._renderEffect);
  53350. var viewMatrix = this._scene.getViewMatrix();
  53351. this._renderEffect.setMatrix("view", viewMatrix);
  53352. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  53353. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  53354. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  53355. if (this._scene.clipPlane) {
  53356. var clipPlane = this._scene.clipPlane;
  53357. var invView = viewMatrix.clone();
  53358. invView.invert();
  53359. this._renderEffect.setMatrix("invView", invView);
  53360. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  53361. }
  53362. // Draw order
  53363. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  53364. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  53365. }
  53366. else {
  53367. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53368. }
  53369. if (this.forceDepthWrite) {
  53370. this._engine.setDepthWrite(true);
  53371. }
  53372. // Bind source VAO
  53373. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  53374. // Render
  53375. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  53376. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53377. // Switch VAOs
  53378. this._targetIndex++;
  53379. if (this._targetIndex === 2) {
  53380. this._targetIndex = 0;
  53381. }
  53382. // Switch buffers
  53383. var tmpBuffer = this._sourceBuffer;
  53384. this._sourceBuffer = this._targetBuffer;
  53385. this._targetBuffer = tmpBuffer;
  53386. return this._currentActiveCount;
  53387. };
  53388. /**
  53389. * Rebuilds the particle system
  53390. */
  53391. GPUParticleSystem.prototype.rebuild = function () {
  53392. this._initialize(true);
  53393. };
  53394. GPUParticleSystem.prototype._releaseBuffers = function () {
  53395. if (this._buffer0) {
  53396. this._buffer0.dispose();
  53397. this._buffer0 = null;
  53398. }
  53399. if (this._buffer1) {
  53400. this._buffer1.dispose();
  53401. this._buffer1 = null;
  53402. }
  53403. if (this._spriteBuffer) {
  53404. this._spriteBuffer.dispose();
  53405. this._spriteBuffer = null;
  53406. }
  53407. };
  53408. GPUParticleSystem.prototype._releaseVAOs = function () {
  53409. if (!this._updateVAO) {
  53410. return;
  53411. }
  53412. for (var index = 0; index < this._updateVAO.length; index++) {
  53413. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  53414. }
  53415. this._updateVAO = [];
  53416. for (var index = 0; index < this._renderVAO.length; index++) {
  53417. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  53418. }
  53419. this._renderVAO = [];
  53420. };
  53421. /**
  53422. * Disposes the particle system and free the associated resources
  53423. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  53424. */
  53425. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  53426. if (disposeTexture === void 0) { disposeTexture = true; }
  53427. var index = this._scene.particleSystems.indexOf(this);
  53428. if (index > -1) {
  53429. this._scene.particleSystems.splice(index, 1);
  53430. }
  53431. this._releaseBuffers();
  53432. this._releaseVAOs();
  53433. if (this._randomTexture) {
  53434. this._randomTexture.dispose();
  53435. this._randomTexture = null;
  53436. }
  53437. if (disposeTexture && this.particleTexture) {
  53438. this.particleTexture.dispose();
  53439. this.particleTexture = null;
  53440. }
  53441. // Callback
  53442. this.onDisposeObservable.notifyObservers(this);
  53443. this.onDisposeObservable.clear();
  53444. };
  53445. /**
  53446. * Clones the particle system.
  53447. * @param name The name of the cloned object
  53448. * @param newEmitter The new emitter to use
  53449. * @returns the cloned particle system
  53450. */
  53451. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  53452. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  53453. BABYLON.Tools.DeepCopy(this, result);
  53454. if (newEmitter === undefined) {
  53455. newEmitter = this.emitter;
  53456. }
  53457. result.emitter = newEmitter;
  53458. if (this.particleTexture) {
  53459. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  53460. }
  53461. return result;
  53462. };
  53463. /**
  53464. * Serializes the particle system to a JSON object.
  53465. * @returns the JSON object
  53466. */
  53467. GPUParticleSystem.prototype.serialize = function () {
  53468. var serializationObject = {};
  53469. serializationObject.name = this.name;
  53470. serializationObject.id = this.id;
  53471. // Emitter
  53472. if (this.emitter.position) {
  53473. var emitterMesh = this.emitter;
  53474. serializationObject.emitterId = emitterMesh.id;
  53475. }
  53476. else {
  53477. var emitterPosition = this.emitter;
  53478. serializationObject.emitter = emitterPosition.asArray();
  53479. }
  53480. serializationObject.capacity = this.getCapacity();
  53481. if (this.particleTexture) {
  53482. serializationObject.textureName = this.particleTexture.name;
  53483. }
  53484. // Animations
  53485. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  53486. // Particle system
  53487. serializationObject.activeParticleCount = this.activeParticleCount;
  53488. serializationObject.randomTextureSize = this._randomTextureSize;
  53489. serializationObject.minSize = this.minSize;
  53490. serializationObject.maxSize = this.maxSize;
  53491. serializationObject.minEmitPower = this.minEmitPower;
  53492. serializationObject.maxEmitPower = this.maxEmitPower;
  53493. serializationObject.minLifeTime = this.minLifeTime;
  53494. serializationObject.maxLifeTime = this.maxLifeTime;
  53495. serializationObject.emitRate = this.emitRate;
  53496. serializationObject.gravity = this.gravity.asArray();
  53497. serializationObject.color1 = this.color1.asArray();
  53498. serializationObject.color2 = this.color2.asArray();
  53499. serializationObject.colorDead = this.colorDead.asArray();
  53500. serializationObject.updateSpeed = this.updateSpeed;
  53501. serializationObject.targetStopDuration = this.targetStopDuration;
  53502. serializationObject.blendMode = this.blendMode;
  53503. // Emitter
  53504. if (this.particleEmitterType) {
  53505. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  53506. }
  53507. return serializationObject;
  53508. };
  53509. /**
  53510. * Parses a JSON object to create a GPU particle system.
  53511. * @param parsedParticleSystem The JSON object to parse
  53512. * @param scene The scene to create the particle system in
  53513. * @param rootUrl The root url to use to load external dependencies like texture
  53514. * @returns the parsed GPU particle system
  53515. */
  53516. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  53517. var name = parsedParticleSystem.name;
  53518. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  53519. if (parsedParticleSystem.id) {
  53520. particleSystem.id = parsedParticleSystem.id;
  53521. }
  53522. // Texture
  53523. if (parsedParticleSystem.textureName) {
  53524. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  53525. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  53526. }
  53527. // Emitter
  53528. if (parsedParticleSystem.emitterId) {
  53529. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  53530. }
  53531. else {
  53532. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  53533. }
  53534. // Animations
  53535. if (parsedParticleSystem.animations) {
  53536. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  53537. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  53538. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  53539. }
  53540. }
  53541. // Particle system
  53542. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  53543. particleSystem.minSize = parsedParticleSystem.minSize;
  53544. particleSystem.maxSize = parsedParticleSystem.maxSize;
  53545. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  53546. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  53547. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  53548. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  53549. particleSystem.emitRate = parsedParticleSystem.emitRate;
  53550. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  53551. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  53552. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  53553. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  53554. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  53555. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  53556. particleSystem.blendMode = parsedParticleSystem.blendMode;
  53557. // Emitter
  53558. if (parsedParticleSystem.particleEmitterType) {
  53559. var emitterType = void 0;
  53560. switch (parsedParticleSystem.particleEmitterType.type) {
  53561. case "SphereEmitter":
  53562. emitterType = new BABYLON.SphereParticleEmitter();
  53563. break;
  53564. case "SphereDirectedParticleEmitter":
  53565. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  53566. break;
  53567. case "ConeEmitter":
  53568. emitterType = new BABYLON.ConeParticleEmitter();
  53569. break;
  53570. case "BoxEmitter":
  53571. default:
  53572. emitterType = new BABYLON.BoxParticleEmitter();
  53573. break;
  53574. }
  53575. emitterType.parse(parsedParticleSystem.particleEmitterType);
  53576. particleSystem.particleEmitterType = emitterType;
  53577. }
  53578. return particleSystem;
  53579. };
  53580. return GPUParticleSystem;
  53581. }());
  53582. BABYLON.GPUParticleSystem = GPUParticleSystem;
  53583. })(BABYLON || (BABYLON = {}));
  53584. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  53585. "use strict";
  53586. var BABYLON;
  53587. (function (BABYLON) {
  53588. /**
  53589. * Represents one particle of a solid particle system.
  53590. * @see SolidParticleSystem
  53591. */
  53592. var SolidParticle = /** @class */ (function () {
  53593. /**
  53594. * Creates a Solid Particle object.
  53595. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  53596. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  53597. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  53598. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  53599. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  53600. * @param shapeId (integer) is the model shape identifier in the SPS.
  53601. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  53602. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  53603. */
  53604. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  53605. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  53606. /**
  53607. * particle global index
  53608. */
  53609. this.idx = 0;
  53610. /**
  53611. * The color of the particle
  53612. */
  53613. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53614. /**
  53615. * The world space position of the particle.
  53616. */
  53617. this.position = BABYLON.Vector3.Zero();
  53618. /**
  53619. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  53620. */
  53621. this.rotation = BABYLON.Vector3.Zero();
  53622. /**
  53623. * The scaling of the particle.
  53624. */
  53625. this.scaling = BABYLON.Vector3.One();
  53626. /**
  53627. * The uvs of the particle.
  53628. */
  53629. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  53630. /**
  53631. * The current speed of the particle.
  53632. */
  53633. this.velocity = BABYLON.Vector3.Zero();
  53634. /**
  53635. * The pivot point in the particle local space.
  53636. */
  53637. this.pivot = BABYLON.Vector3.Zero();
  53638. /**
  53639. * Must the particle be translated from its pivot point in its local space ?
  53640. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  53641. * Default : false
  53642. */
  53643. this.translateFromPivot = false;
  53644. /**
  53645. * Is the particle active or not ?
  53646. */
  53647. this.alive = true;
  53648. /**
  53649. * Is the particle visible or not ?
  53650. */
  53651. this.isVisible = true;
  53652. /**
  53653. * Index of this particle in the global "positions" array (Internal use)
  53654. */
  53655. this._pos = 0;
  53656. /**
  53657. * Index of this particle in the global "indices" array (Internal use)
  53658. */
  53659. this._ind = 0;
  53660. /**
  53661. * ModelShape id of this particle
  53662. */
  53663. this.shapeId = 0;
  53664. /**
  53665. * Index of the particle in its shape id (Internal use)
  53666. */
  53667. this.idxInShape = 0;
  53668. /**
  53669. * Still set as invisible in order to skip useless computations (Internal use)
  53670. */
  53671. this._stillInvisible = false;
  53672. /**
  53673. * Last computed particle rotation matrix
  53674. */
  53675. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  53676. /**
  53677. * Parent particle Id, if any.
  53678. * Default null.
  53679. */
  53680. this.parentId = null;
  53681. /**
  53682. * Internal global position in the SPS.
  53683. */
  53684. this._globalPosition = BABYLON.Vector3.Zero();
  53685. this.idx = particleIndex;
  53686. this._pos = positionIndex;
  53687. this._ind = indiceIndex;
  53688. this._model = model;
  53689. this.shapeId = shapeId;
  53690. this.idxInShape = idxInShape;
  53691. this._sps = sps;
  53692. if (modelBoundingInfo) {
  53693. this._modelBoundingInfo = modelBoundingInfo;
  53694. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  53695. }
  53696. }
  53697. Object.defineProperty(SolidParticle.prototype, "scale", {
  53698. /**
  53699. * Legacy support, changed scale to scaling
  53700. */
  53701. get: function () {
  53702. return this.scaling;
  53703. },
  53704. /**
  53705. * Legacy support, changed scale to scaling
  53706. */
  53707. set: function (scale) {
  53708. this.scaling = scale;
  53709. },
  53710. enumerable: true,
  53711. configurable: true
  53712. });
  53713. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  53714. /**
  53715. * Legacy support, changed quaternion to rotationQuaternion
  53716. */
  53717. get: function () {
  53718. return this.rotationQuaternion;
  53719. },
  53720. /**
  53721. * Legacy support, changed quaternion to rotationQuaternion
  53722. */
  53723. set: function (q) {
  53724. this.rotationQuaternion = q;
  53725. },
  53726. enumerable: true,
  53727. configurable: true
  53728. });
  53729. /**
  53730. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  53731. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  53732. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  53733. * @returns true if it intersects
  53734. */
  53735. SolidParticle.prototype.intersectsMesh = function (target) {
  53736. if (!this._boundingInfo || !target._boundingInfo) {
  53737. return false;
  53738. }
  53739. if (this._sps._bSphereOnly) {
  53740. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  53741. }
  53742. return this._boundingInfo.intersects(target._boundingInfo, false);
  53743. };
  53744. return SolidParticle;
  53745. }());
  53746. BABYLON.SolidParticle = SolidParticle;
  53747. /**
  53748. * Represents the shape of the model used by one particle of a solid particle system.
  53749. * SPS internal tool, don't use it manually.
  53750. * @see SolidParticleSystem
  53751. */
  53752. var ModelShape = /** @class */ (function () {
  53753. /**
  53754. * 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.
  53755. * SPS internal tool, don't use it manually.
  53756. * @ignore
  53757. */
  53758. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  53759. /**
  53760. * length of the shape in the model indices array (internal use)
  53761. */
  53762. this._indicesLength = 0;
  53763. this.shapeID = id;
  53764. this._shape = shape;
  53765. this._indicesLength = indicesLength;
  53766. this._shapeUV = shapeUV;
  53767. this._positionFunction = posFunction;
  53768. this._vertexFunction = vtxFunction;
  53769. }
  53770. return ModelShape;
  53771. }());
  53772. BABYLON.ModelShape = ModelShape;
  53773. /**
  53774. * Represents a Depth Sorted Particle in the solid particle system.
  53775. * @see SolidParticleSystem
  53776. */
  53777. var DepthSortedParticle = /** @class */ (function () {
  53778. function DepthSortedParticle() {
  53779. /**
  53780. * Index of the particle in the "indices" array
  53781. */
  53782. this.ind = 0;
  53783. /**
  53784. * Length of the particle shape in the "indices" array
  53785. */
  53786. this.indicesLength = 0;
  53787. /**
  53788. * Squared distance from the particle to the camera
  53789. */
  53790. this.sqDistance = 0.0;
  53791. }
  53792. return DepthSortedParticle;
  53793. }());
  53794. BABYLON.DepthSortedParticle = DepthSortedParticle;
  53795. })(BABYLON || (BABYLON = {}));
  53796. //# sourceMappingURL=babylon.solidParticle.js.map
  53797. "use strict";
  53798. var BABYLON;
  53799. (function (BABYLON) {
  53800. /**
  53801. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  53802. *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.
  53803. * The SPS is also a particle system. It provides some methods to manage the particles.
  53804. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  53805. *
  53806. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  53807. */
  53808. var SolidParticleSystem = /** @class */ (function () {
  53809. /**
  53810. * Creates a SPS (Solid Particle System) object.
  53811. * @param name (String) is the SPS name, this will be the underlying mesh name.
  53812. * @param scene (Scene) is the scene in which the SPS is added.
  53813. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  53814. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  53815. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  53816. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  53817. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  53818. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  53819. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  53820. */
  53821. function SolidParticleSystem(name, scene, options) {
  53822. /**
  53823. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  53824. * Example : var p = SPS.particles[i];
  53825. */
  53826. this.particles = new Array();
  53827. /**
  53828. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  53829. */
  53830. this.nbParticles = 0;
  53831. /**
  53832. * If the particles must ever face the camera (default false). Useful for planar particles.
  53833. */
  53834. this.billboard = false;
  53835. /**
  53836. * Recompute normals when adding a shape
  53837. */
  53838. this.recomputeNormals = true;
  53839. /**
  53840. * This a counter ofr your own usage. It's not set by any SPS functions.
  53841. */
  53842. this.counter = 0;
  53843. /**
  53844. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  53845. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  53846. */
  53847. this.vars = {};
  53848. /**
  53849. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  53850. */
  53851. this._bSphereOnly = false;
  53852. /**
  53853. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  53854. */
  53855. this._bSphereRadiusFactor = 1.0;
  53856. this._positions = new Array();
  53857. this._indices = new Array();
  53858. this._normals = new Array();
  53859. this._colors = new Array();
  53860. this._uvs = new Array();
  53861. this._index = 0; // indices index
  53862. this._updatable = true;
  53863. this._pickable = false;
  53864. this._isVisibilityBoxLocked = false;
  53865. this._alwaysVisible = false;
  53866. this._depthSort = false;
  53867. this._shapeCounter = 0;
  53868. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  53869. this._color = new BABYLON.Color4(0, 0, 0, 0);
  53870. this._computeParticleColor = true;
  53871. this._computeParticleTexture = true;
  53872. this._computeParticleRotation = true;
  53873. this._computeParticleVertex = false;
  53874. this._computeBoundingBox = false;
  53875. this._depthSortParticles = true;
  53876. this._cam_axisZ = BABYLON.Vector3.Zero();
  53877. this._cam_axisY = BABYLON.Vector3.Zero();
  53878. this._cam_axisX = BABYLON.Vector3.Zero();
  53879. this._axisZ = BABYLON.Axis.Z;
  53880. this._camDir = BABYLON.Vector3.Zero();
  53881. this._camInvertedPosition = BABYLON.Vector3.Zero();
  53882. this._rotMatrix = new BABYLON.Matrix();
  53883. this._invertMatrix = new BABYLON.Matrix();
  53884. this._rotated = BABYLON.Vector3.Zero();
  53885. this._quaternion = new BABYLON.Quaternion();
  53886. this._vertex = BABYLON.Vector3.Zero();
  53887. this._normal = BABYLON.Vector3.Zero();
  53888. this._yaw = 0.0;
  53889. this._pitch = 0.0;
  53890. this._roll = 0.0;
  53891. this._halfroll = 0.0;
  53892. this._halfpitch = 0.0;
  53893. this._halfyaw = 0.0;
  53894. this._sinRoll = 0.0;
  53895. this._cosRoll = 0.0;
  53896. this._sinPitch = 0.0;
  53897. this._cosPitch = 0.0;
  53898. this._sinYaw = 0.0;
  53899. this._cosYaw = 0.0;
  53900. this._mustUnrotateFixedNormals = false;
  53901. this._minimum = BABYLON.Vector3.Zero();
  53902. this._maximum = BABYLON.Vector3.Zero();
  53903. this._minBbox = BABYLON.Vector3.Zero();
  53904. this._maxBbox = BABYLON.Vector3.Zero();
  53905. this._particlesIntersect = false;
  53906. this._depthSortFunction = function (p1, p2) {
  53907. return (p2.sqDistance - p1.sqDistance);
  53908. };
  53909. this._needs32Bits = false;
  53910. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  53911. this._scaledPivot = BABYLON.Vector3.Zero();
  53912. this._particleHasParent = false;
  53913. this.name = name;
  53914. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53915. this._camera = scene.activeCamera;
  53916. this._pickable = options ? options.isPickable : false;
  53917. this._depthSort = options ? options.enableDepthSort : false;
  53918. this._particlesIntersect = options ? options.particleIntersection : false;
  53919. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  53920. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  53921. if (options && options.updatable) {
  53922. this._updatable = options.updatable;
  53923. }
  53924. else {
  53925. this._updatable = true;
  53926. }
  53927. if (this._pickable) {
  53928. this.pickedParticles = [];
  53929. }
  53930. if (this._depthSort) {
  53931. this.depthSortedParticles = [];
  53932. }
  53933. }
  53934. /**
  53935. * Builds the SPS underlying mesh. Returns a standard Mesh.
  53936. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  53937. * @returns the created mesh
  53938. */
  53939. SolidParticleSystem.prototype.buildMesh = function () {
  53940. if (this.nbParticles === 0) {
  53941. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  53942. this.addShape(triangle, 1);
  53943. triangle.dispose();
  53944. }
  53945. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  53946. this._positions32 = new Float32Array(this._positions);
  53947. this._uvs32 = new Float32Array(this._uvs);
  53948. this._colors32 = new Float32Array(this._colors);
  53949. if (this.recomputeNormals) {
  53950. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  53951. }
  53952. this._normals32 = new Float32Array(this._normals);
  53953. this._fixedNormal32 = new Float32Array(this._normals);
  53954. if (this._mustUnrotateFixedNormals) {
  53955. this._unrotateFixedNormals();
  53956. }
  53957. var vertexData = new BABYLON.VertexData();
  53958. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  53959. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  53960. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  53961. if (this._uvs32) {
  53962. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  53963. ;
  53964. }
  53965. if (this._colors32) {
  53966. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  53967. }
  53968. var mesh = new BABYLON.Mesh(this.name, this._scene);
  53969. vertexData.applyToMesh(mesh, this._updatable);
  53970. this.mesh = mesh;
  53971. this.mesh.isPickable = this._pickable;
  53972. // free memory
  53973. if (!this._depthSort) {
  53974. this._indices = null;
  53975. }
  53976. this._positions = null;
  53977. this._normals = null;
  53978. this._uvs = null;
  53979. this._colors = null;
  53980. if (!this._updatable) {
  53981. this.particles.length = 0;
  53982. }
  53983. return mesh;
  53984. };
  53985. /**
  53986. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  53987. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  53988. * Thus the particles generated from `digest()` have their property `position` set yet.
  53989. * @param mesh ( Mesh ) is the mesh to be digested
  53990. * @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
  53991. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  53992. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  53993. * @returns the current SPS
  53994. */
  53995. SolidParticleSystem.prototype.digest = function (mesh, options) {
  53996. var size = (options && options.facetNb) || 1;
  53997. var number = (options && options.number) || 0;
  53998. var delta = (options && options.delta) || 0;
  53999. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54000. var meshInd = mesh.getIndices();
  54001. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54002. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54003. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54004. var f = 0; // facet counter
  54005. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  54006. // compute size from number
  54007. if (number) {
  54008. number = (number > totalFacets) ? totalFacets : number;
  54009. size = Math.round(totalFacets / number);
  54010. delta = 0;
  54011. }
  54012. else {
  54013. size = (size > totalFacets) ? totalFacets : size;
  54014. }
  54015. var facetPos = []; // submesh positions
  54016. var facetInd = []; // submesh indices
  54017. var facetUV = []; // submesh UV
  54018. var facetCol = []; // submesh colors
  54019. var barycenter = BABYLON.Vector3.Zero();
  54020. var sizeO = size;
  54021. while (f < totalFacets) {
  54022. size = sizeO + Math.floor((1 + delta) * Math.random());
  54023. if (f > totalFacets - size) {
  54024. size = totalFacets - f;
  54025. }
  54026. // reset temp arrays
  54027. facetPos.length = 0;
  54028. facetInd.length = 0;
  54029. facetUV.length = 0;
  54030. facetCol.length = 0;
  54031. // iterate over "size" facets
  54032. var fi = 0;
  54033. for (var j = f * 3; j < (f + size) * 3; j++) {
  54034. facetInd.push(fi);
  54035. var i = meshInd[j];
  54036. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  54037. if (meshUV) {
  54038. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  54039. }
  54040. if (meshCol) {
  54041. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  54042. }
  54043. fi++;
  54044. }
  54045. // create a model shape for each single particle
  54046. var idx = this.nbParticles;
  54047. var shape = this._posToShape(facetPos);
  54048. var shapeUV = this._uvsToShapeUV(facetUV);
  54049. // compute the barycenter of the shape
  54050. var v;
  54051. for (v = 0; v < shape.length; v++) {
  54052. barycenter.addInPlace(shape[v]);
  54053. }
  54054. barycenter.scaleInPlace(1 / shape.length);
  54055. // shift the shape from its barycenter to the origin
  54056. for (v = 0; v < shape.length; v++) {
  54057. shape[v].subtractInPlace(barycenter);
  54058. }
  54059. var bInfo;
  54060. if (this._particlesIntersect) {
  54061. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  54062. }
  54063. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  54064. // add the particle in the SPS
  54065. var currentPos = this._positions.length;
  54066. var currentInd = this._indices.length;
  54067. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  54068. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  54069. // initialize the particle position
  54070. this.particles[this.nbParticles].position.addInPlace(barycenter);
  54071. this._index += shape.length;
  54072. idx++;
  54073. this.nbParticles++;
  54074. this._shapeCounter++;
  54075. f += size;
  54076. }
  54077. return this;
  54078. };
  54079. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  54080. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  54081. var index = 0;
  54082. var idx = 0;
  54083. for (var p = 0; p < this.particles.length; p++) {
  54084. this._particle = this.particles[p];
  54085. this._shape = this._particle._model._shape;
  54086. if (this._particle.rotationQuaternion) {
  54087. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  54088. }
  54089. else {
  54090. this._yaw = this._particle.rotation.y;
  54091. this._pitch = this._particle.rotation.x;
  54092. this._roll = this._particle.rotation.z;
  54093. this._quaternionRotationYPR();
  54094. }
  54095. this._quaternionToRotationMatrix();
  54096. this._rotMatrix.invertToRef(this._invertMatrix);
  54097. for (var pt = 0; pt < this._shape.length; pt++) {
  54098. idx = index + pt * 3;
  54099. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  54100. this._fixedNormal32[idx] = this._normal.x;
  54101. this._fixedNormal32[idx + 1] = this._normal.y;
  54102. this._fixedNormal32[idx + 2] = this._normal.z;
  54103. }
  54104. index = idx + 3;
  54105. }
  54106. };
  54107. //reset copy
  54108. SolidParticleSystem.prototype._resetCopy = function () {
  54109. this._copy.position.x = 0;
  54110. this._copy.position.y = 0;
  54111. this._copy.position.z = 0;
  54112. this._copy.rotation.x = 0;
  54113. this._copy.rotation.y = 0;
  54114. this._copy.rotation.z = 0;
  54115. this._copy.rotationQuaternion = null;
  54116. this._copy.scaling.x = 1.0;
  54117. this._copy.scaling.y = 1.0;
  54118. this._copy.scaling.z = 1.0;
  54119. this._copy.uvs.x = 0;
  54120. this._copy.uvs.y = 0;
  54121. this._copy.uvs.z = 1.0;
  54122. this._copy.uvs.w = 1.0;
  54123. this._copy.color = null;
  54124. this._copy.translateFromPivot = false;
  54125. };
  54126. // _meshBuilder : inserts the shape model in the global SPS mesh
  54127. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  54128. var i;
  54129. var u = 0;
  54130. var c = 0;
  54131. var n = 0;
  54132. this._resetCopy();
  54133. if (options && options.positionFunction) {
  54134. options.positionFunction(this._copy, idx, idxInShape);
  54135. this._mustUnrotateFixedNormals = true;
  54136. }
  54137. if (this._copy.rotationQuaternion) {
  54138. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  54139. }
  54140. else {
  54141. this._yaw = this._copy.rotation.y;
  54142. this._pitch = this._copy.rotation.x;
  54143. this._roll = this._copy.rotation.z;
  54144. this._quaternionRotationYPR();
  54145. }
  54146. this._quaternionToRotationMatrix();
  54147. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  54148. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  54149. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  54150. if (this._copy.translateFromPivot) {
  54151. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  54152. }
  54153. else {
  54154. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  54155. }
  54156. for (i = 0; i < shape.length; i++) {
  54157. this._vertex.x = shape[i].x;
  54158. this._vertex.y = shape[i].y;
  54159. this._vertex.z = shape[i].z;
  54160. if (options && options.vertexFunction) {
  54161. options.vertexFunction(this._copy, this._vertex, i);
  54162. }
  54163. this._vertex.x *= this._copy.scaling.x;
  54164. this._vertex.y *= this._copy.scaling.y;
  54165. this._vertex.z *= this._copy.scaling.z;
  54166. this._vertex.x -= this._scaledPivot.x;
  54167. this._vertex.y -= this._scaledPivot.y;
  54168. this._vertex.z -= this._scaledPivot.z;
  54169. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  54170. this._rotated.addInPlace(this._pivotBackTranslation);
  54171. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  54172. if (meshUV) {
  54173. 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);
  54174. u += 2;
  54175. }
  54176. if (this._copy.color) {
  54177. this._color = this._copy.color;
  54178. }
  54179. else if (meshCol && meshCol[c] !== undefined) {
  54180. this._color.r = meshCol[c];
  54181. this._color.g = meshCol[c + 1];
  54182. this._color.b = meshCol[c + 2];
  54183. this._color.a = meshCol[c + 3];
  54184. }
  54185. else {
  54186. this._color.r = 1.0;
  54187. this._color.g = 1.0;
  54188. this._color.b = 1.0;
  54189. this._color.a = 1.0;
  54190. }
  54191. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  54192. c += 4;
  54193. if (!this.recomputeNormals && meshNor) {
  54194. this._normal.x = meshNor[n];
  54195. this._normal.y = meshNor[n + 1];
  54196. this._normal.z = meshNor[n + 2];
  54197. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  54198. normals.push(this._normal.x, this._normal.y, this._normal.z);
  54199. n += 3;
  54200. }
  54201. }
  54202. for (i = 0; i < meshInd.length; i++) {
  54203. var current_ind = p + meshInd[i];
  54204. indices.push(current_ind);
  54205. if (current_ind > 65535) {
  54206. this._needs32Bits = true;
  54207. }
  54208. }
  54209. if (this._pickable) {
  54210. var nbfaces = meshInd.length / 3;
  54211. for (i = 0; i < nbfaces; i++) {
  54212. this.pickedParticles.push({ idx: idx, faceId: i });
  54213. }
  54214. }
  54215. if (this._depthSort) {
  54216. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  54217. }
  54218. return this._copy;
  54219. };
  54220. // returns a shape array from positions array
  54221. SolidParticleSystem.prototype._posToShape = function (positions) {
  54222. var shape = [];
  54223. for (var i = 0; i < positions.length; i += 3) {
  54224. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  54225. }
  54226. return shape;
  54227. };
  54228. // returns a shapeUV array from a Vector4 uvs
  54229. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  54230. var shapeUV = [];
  54231. if (uvs) {
  54232. for (var i = 0; i < uvs.length; i++)
  54233. shapeUV.push(uvs[i]);
  54234. }
  54235. return shapeUV;
  54236. };
  54237. // adds a new particle object in the particles array
  54238. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  54239. if (bInfo === void 0) { bInfo = null; }
  54240. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  54241. this.particles.push(sp);
  54242. return sp;
  54243. };
  54244. /**
  54245. * Adds some particles to the SPS from the model shape. Returns the shape id.
  54246. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  54247. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  54248. * @param nb (positive integer) the number of particles to be created from this model
  54249. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  54250. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  54251. * @returns the number of shapes in the system
  54252. */
  54253. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  54254. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54255. var meshInd = mesh.getIndices();
  54256. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54257. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  54258. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54259. var bbInfo;
  54260. if (this._particlesIntersect) {
  54261. bbInfo = mesh.getBoundingInfo();
  54262. }
  54263. var shape = this._posToShape(meshPos);
  54264. var shapeUV = this._uvsToShapeUV(meshUV);
  54265. var posfunc = options ? options.positionFunction : null;
  54266. var vtxfunc = options ? options.vertexFunction : null;
  54267. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  54268. // particles
  54269. var sp;
  54270. var currentCopy;
  54271. var idx = this.nbParticles;
  54272. for (var i = 0; i < nb; i++) {
  54273. var currentPos = this._positions.length;
  54274. var currentInd = this._indices.length;
  54275. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  54276. if (this._updatable) {
  54277. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  54278. sp.position.copyFrom(currentCopy.position);
  54279. sp.rotation.copyFrom(currentCopy.rotation);
  54280. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  54281. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  54282. }
  54283. if (currentCopy.color && sp.color) {
  54284. sp.color.copyFrom(currentCopy.color);
  54285. }
  54286. sp.scaling.copyFrom(currentCopy.scaling);
  54287. sp.uvs.copyFrom(currentCopy.uvs);
  54288. }
  54289. this._index += shape.length;
  54290. idx++;
  54291. }
  54292. this.nbParticles += nb;
  54293. this._shapeCounter++;
  54294. return this._shapeCounter - 1;
  54295. };
  54296. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  54297. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  54298. this._resetCopy();
  54299. if (particle._model._positionFunction) {
  54300. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  54301. }
  54302. if (this._copy.rotationQuaternion) {
  54303. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  54304. }
  54305. else {
  54306. this._yaw = this._copy.rotation.y;
  54307. this._pitch = this._copy.rotation.x;
  54308. this._roll = this._copy.rotation.z;
  54309. this._quaternionRotationYPR();
  54310. }
  54311. this._quaternionToRotationMatrix();
  54312. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  54313. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  54314. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  54315. if (this._copy.translateFromPivot) {
  54316. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  54317. }
  54318. else {
  54319. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  54320. }
  54321. this._shape = particle._model._shape;
  54322. for (var pt = 0; pt < this._shape.length; pt++) {
  54323. this._vertex.x = this._shape[pt].x;
  54324. this._vertex.y = this._shape[pt].y;
  54325. this._vertex.z = this._shape[pt].z;
  54326. if (particle._model._vertexFunction) {
  54327. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  54328. }
  54329. this._vertex.x *= this._copy.scaling.x;
  54330. this._vertex.y *= this._copy.scaling.y;
  54331. this._vertex.z *= this._copy.scaling.z;
  54332. this._vertex.x -= this._scaledPivot.x;
  54333. this._vertex.y -= this._scaledPivot.y;
  54334. this._vertex.z -= this._scaledPivot.z;
  54335. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  54336. this._rotated.addInPlace(this._pivotBackTranslation);
  54337. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  54338. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  54339. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  54340. }
  54341. particle.position.x = 0.0;
  54342. particle.position.y = 0.0;
  54343. particle.position.z = 0.0;
  54344. particle.rotation.x = 0.0;
  54345. particle.rotation.y = 0.0;
  54346. particle.rotation.z = 0.0;
  54347. particle.rotationQuaternion = null;
  54348. particle.scaling.x = 1.0;
  54349. particle.scaling.y = 1.0;
  54350. particle.scaling.z = 1.0;
  54351. particle.uvs.x = 0.0;
  54352. particle.uvs.y = 0.0;
  54353. particle.uvs.z = 1.0;
  54354. particle.uvs.w = 1.0;
  54355. particle.pivot.x = 0.0;
  54356. particle.pivot.y = 0.0;
  54357. particle.pivot.z = 0.0;
  54358. particle.translateFromPivot = false;
  54359. particle.parentId = null;
  54360. };
  54361. /**
  54362. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  54363. * @returns the SPS.
  54364. */
  54365. SolidParticleSystem.prototype.rebuildMesh = function () {
  54366. for (var p = 0; p < this.particles.length; p++) {
  54367. this._rebuildParticle(this.particles[p]);
  54368. }
  54369. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  54370. return this;
  54371. };
  54372. /**
  54373. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  54374. * This method calls `updateParticle()` for each particle of the SPS.
  54375. * For an animated SPS, it is usually called within the render loop.
  54376. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  54377. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  54378. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  54379. * @returns the SPS.
  54380. */
  54381. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  54382. if (start === void 0) { start = 0; }
  54383. if (end === void 0) { end = this.nbParticles - 1; }
  54384. if (update === void 0) { update = true; }
  54385. if (!this._updatable) {
  54386. return this;
  54387. }
  54388. // custom beforeUpdate
  54389. this.beforeUpdateParticles(start, end, update);
  54390. this._cam_axisX.x = 1.0;
  54391. this._cam_axisX.y = 0.0;
  54392. this._cam_axisX.z = 0.0;
  54393. this._cam_axisY.x = 0.0;
  54394. this._cam_axisY.y = 1.0;
  54395. this._cam_axisY.z = 0.0;
  54396. this._cam_axisZ.x = 0.0;
  54397. this._cam_axisZ.y = 0.0;
  54398. this._cam_axisZ.z = 1.0;
  54399. // cases when the World Matrix is to be computed first
  54400. if (this.billboard || this._depthSort) {
  54401. this.mesh.computeWorldMatrix(true);
  54402. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  54403. }
  54404. // if the particles will always face the camera
  54405. if (this.billboard) {
  54406. // compute the camera position and un-rotate it by the current mesh rotation
  54407. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  54408. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  54409. this._cam_axisZ.normalize();
  54410. // same for camera up vector extracted from the cam view matrix
  54411. var view = this._camera.getViewMatrix(true);
  54412. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  54413. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  54414. this._cam_axisY.normalize();
  54415. this._cam_axisX.normalize();
  54416. }
  54417. // if depthSort, compute the camera global position in the mesh local system
  54418. if (this._depthSort) {
  54419. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  54420. }
  54421. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  54422. var idx = 0; // current position index in the global array positions32
  54423. var index = 0; // position start index in the global array positions32 of the current particle
  54424. var colidx = 0; // current color index in the global array colors32
  54425. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  54426. var uvidx = 0; // current uv index in the global array uvs32
  54427. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  54428. var pt = 0; // current index in the particle model shape
  54429. if (this.mesh.isFacetDataEnabled) {
  54430. this._computeBoundingBox = true;
  54431. }
  54432. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  54433. if (this._computeBoundingBox) {
  54434. if (start == 0 && end == this.nbParticles - 1) {
  54435. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  54436. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  54437. }
  54438. else {
  54439. if (this.mesh._boundingInfo) {
  54440. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  54441. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  54442. }
  54443. }
  54444. }
  54445. // particle loop
  54446. index = this.particles[start]._pos;
  54447. var vpos = (index / 3) | 0;
  54448. colorIndex = vpos * 4;
  54449. uvIndex = vpos * 2;
  54450. for (var p = start; p <= end; p++) {
  54451. this._particle = this.particles[p];
  54452. this._shape = this._particle._model._shape;
  54453. this._shapeUV = this._particle._model._shapeUV;
  54454. // call to custom user function to update the particle properties
  54455. this.updateParticle(this._particle);
  54456. // camera-particle distance for depth sorting
  54457. if (this._depthSort && this._depthSortParticles) {
  54458. var dsp = this.depthSortedParticles[p];
  54459. dsp.ind = this._particle._ind;
  54460. dsp.indicesLength = this._particle._model._indicesLength;
  54461. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  54462. }
  54463. // skip the computations for inactive or already invisible particles
  54464. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  54465. // increment indexes for the next particle
  54466. pt = this._shape.length;
  54467. index += pt * 3;
  54468. colorIndex += pt * 4;
  54469. uvIndex += pt * 2;
  54470. continue;
  54471. }
  54472. if (this._particle.isVisible) {
  54473. this._particle._stillInvisible = false; // un-mark permanent invisibility
  54474. this._particleHasParent = (this._particle.parentId !== null);
  54475. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  54476. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  54477. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  54478. // particle rotation matrix
  54479. if (this.billboard) {
  54480. this._particle.rotation.x = 0.0;
  54481. this._particle.rotation.y = 0.0;
  54482. }
  54483. if (this._computeParticleRotation || this.billboard) {
  54484. if (this._particle.rotationQuaternion) {
  54485. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  54486. }
  54487. else {
  54488. this._yaw = this._particle.rotation.y;
  54489. this._pitch = this._particle.rotation.x;
  54490. this._roll = this._particle.rotation.z;
  54491. this._quaternionRotationYPR();
  54492. }
  54493. this._quaternionToRotationMatrix();
  54494. }
  54495. if (this._particleHasParent) {
  54496. this._parent = this.particles[this._particle.parentId];
  54497. 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];
  54498. 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];
  54499. 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];
  54500. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  54501. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  54502. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  54503. if (this._computeParticleRotation || this.billboard) {
  54504. 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];
  54505. 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];
  54506. 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];
  54507. 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];
  54508. 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];
  54509. 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];
  54510. 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];
  54511. 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];
  54512. 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];
  54513. }
  54514. }
  54515. else {
  54516. this._particle._globalPosition.x = this._particle.position.x;
  54517. this._particle._globalPosition.y = this._particle.position.y;
  54518. this._particle._globalPosition.z = this._particle.position.z;
  54519. if (this._computeParticleRotation || this.billboard) {
  54520. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  54521. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  54522. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  54523. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  54524. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  54525. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  54526. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  54527. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  54528. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  54529. }
  54530. }
  54531. if (this._particle.translateFromPivot) {
  54532. this._pivotBackTranslation.x = 0.0;
  54533. this._pivotBackTranslation.y = 0.0;
  54534. this._pivotBackTranslation.z = 0.0;
  54535. }
  54536. else {
  54537. this._pivotBackTranslation.x = this._scaledPivot.x;
  54538. this._pivotBackTranslation.y = this._scaledPivot.y;
  54539. this._pivotBackTranslation.z = this._scaledPivot.z;
  54540. }
  54541. // particle vertex loop
  54542. for (pt = 0; pt < this._shape.length; pt++) {
  54543. idx = index + pt * 3;
  54544. colidx = colorIndex + pt * 4;
  54545. uvidx = uvIndex + pt * 2;
  54546. this._vertex.x = this._shape[pt].x;
  54547. this._vertex.y = this._shape[pt].y;
  54548. this._vertex.z = this._shape[pt].z;
  54549. if (this._computeParticleVertex) {
  54550. this.updateParticleVertex(this._particle, this._vertex, pt);
  54551. }
  54552. // positions
  54553. this._vertex.x *= this._particle.scaling.x;
  54554. this._vertex.y *= this._particle.scaling.y;
  54555. this._vertex.z *= this._particle.scaling.z;
  54556. this._vertex.x -= this._scaledPivot.x;
  54557. this._vertex.y -= this._scaledPivot.y;
  54558. this._vertex.z -= this._scaledPivot.z;
  54559. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  54560. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  54561. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  54562. this._rotated.x += this._pivotBackTranslation.x;
  54563. this._rotated.y += this._pivotBackTranslation.y;
  54564. this._rotated.z += this._pivotBackTranslation.z;
  54565. 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;
  54566. 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;
  54567. 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;
  54568. if (this._computeBoundingBox) {
  54569. if (this._positions32[idx] < this._minimum.x) {
  54570. this._minimum.x = this._positions32[idx];
  54571. }
  54572. if (this._positions32[idx] > this._maximum.x) {
  54573. this._maximum.x = this._positions32[idx];
  54574. }
  54575. if (this._positions32[idx + 1] < this._minimum.y) {
  54576. this._minimum.y = this._positions32[idx + 1];
  54577. }
  54578. if (this._positions32[idx + 1] > this._maximum.y) {
  54579. this._maximum.y = this._positions32[idx + 1];
  54580. }
  54581. if (this._positions32[idx + 2] < this._minimum.z) {
  54582. this._minimum.z = this._positions32[idx + 2];
  54583. }
  54584. if (this._positions32[idx + 2] > this._maximum.z) {
  54585. this._maximum.z = this._positions32[idx + 2];
  54586. }
  54587. }
  54588. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  54589. if (!this._computeParticleVertex) {
  54590. this._normal.x = this._fixedNormal32[idx];
  54591. this._normal.y = this._fixedNormal32[idx + 1];
  54592. this._normal.z = this._fixedNormal32[idx + 2];
  54593. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  54594. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  54595. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  54596. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  54597. 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;
  54598. 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;
  54599. }
  54600. if (this._computeParticleColor && this._particle.color) {
  54601. this._colors32[colidx] = this._particle.color.r;
  54602. this._colors32[colidx + 1] = this._particle.color.g;
  54603. this._colors32[colidx + 2] = this._particle.color.b;
  54604. this._colors32[colidx + 3] = this._particle.color.a;
  54605. }
  54606. if (this._computeParticleTexture) {
  54607. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  54608. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  54609. }
  54610. }
  54611. }
  54612. else {
  54613. this._particle._stillInvisible = true; // mark the particle as invisible
  54614. for (pt = 0; pt < this._shape.length; pt++) {
  54615. idx = index + pt * 3;
  54616. colidx = colorIndex + pt * 4;
  54617. uvidx = uvIndex + pt * 2;
  54618. this._positions32[idx] = 0.0;
  54619. this._positions32[idx + 1] = 0.0;
  54620. this._positions32[idx + 2] = 0.0;
  54621. this._normals32[idx] = 0.0;
  54622. this._normals32[idx + 1] = 0.0;
  54623. this._normals32[idx + 2] = 0.0;
  54624. if (this._computeParticleColor && this._particle.color) {
  54625. this._colors32[colidx] = this._particle.color.r;
  54626. this._colors32[colidx + 1] = this._particle.color.g;
  54627. this._colors32[colidx + 2] = this._particle.color.b;
  54628. this._colors32[colidx + 3] = this._particle.color.a;
  54629. }
  54630. if (this._computeParticleTexture) {
  54631. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  54632. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  54633. }
  54634. }
  54635. }
  54636. // if the particle intersections must be computed : update the bbInfo
  54637. if (this._particlesIntersect) {
  54638. var bInfo = this._particle._boundingInfo;
  54639. var bBox = bInfo.boundingBox;
  54640. var bSphere = bInfo.boundingSphere;
  54641. if (!this._bSphereOnly) {
  54642. // place, scale and rotate the particle bbox within the SPS local system, then update it
  54643. for (var b = 0; b < bBox.vectors.length; b++) {
  54644. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  54645. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  54646. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  54647. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  54648. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  54649. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  54650. 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;
  54651. 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;
  54652. 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;
  54653. }
  54654. bBox._update(this.mesh._worldMatrix);
  54655. }
  54656. // place and scale the particle bouding sphere in the SPS local system, then update it
  54657. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  54658. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  54659. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  54660. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  54661. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  54662. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  54663. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  54664. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  54665. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  54666. 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));
  54667. bSphere._update(this.mesh._worldMatrix);
  54668. }
  54669. // increment indexes for the next particle
  54670. index = idx + 3;
  54671. colorIndex = colidx + 4;
  54672. uvIndex = uvidx + 2;
  54673. }
  54674. // if the VBO must be updated
  54675. if (update) {
  54676. if (this._computeParticleColor) {
  54677. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  54678. }
  54679. if (this._computeParticleTexture) {
  54680. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  54681. }
  54682. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  54683. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  54684. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  54685. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  54686. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  54687. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  54688. for (var i = 0; i < this._normals32.length; i++) {
  54689. this._fixedNormal32[i] = this._normals32[i];
  54690. }
  54691. }
  54692. if (!this.mesh.areNormalsFrozen) {
  54693. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  54694. }
  54695. }
  54696. if (this._depthSort && this._depthSortParticles) {
  54697. this.depthSortedParticles.sort(this._depthSortFunction);
  54698. var dspl = this.depthSortedParticles.length;
  54699. var sorted = 0;
  54700. var lind = 0;
  54701. var sind = 0;
  54702. var sid = 0;
  54703. for (sorted = 0; sorted < dspl; sorted++) {
  54704. lind = this.depthSortedParticles[sorted].indicesLength;
  54705. sind = this.depthSortedParticles[sorted].ind;
  54706. for (var i = 0; i < lind; i++) {
  54707. this._indices32[sid] = this._indices[sind + i];
  54708. sid++;
  54709. }
  54710. }
  54711. this.mesh.updateIndices(this._indices32);
  54712. }
  54713. }
  54714. if (this._computeBoundingBox) {
  54715. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  54716. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  54717. }
  54718. this.afterUpdateParticles(start, end, update);
  54719. return this;
  54720. };
  54721. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  54722. this._halfroll = this._roll * 0.5;
  54723. this._halfpitch = this._pitch * 0.5;
  54724. this._halfyaw = this._yaw * 0.5;
  54725. this._sinRoll = Math.sin(this._halfroll);
  54726. this._cosRoll = Math.cos(this._halfroll);
  54727. this._sinPitch = Math.sin(this._halfpitch);
  54728. this._cosPitch = Math.cos(this._halfpitch);
  54729. this._sinYaw = Math.sin(this._halfyaw);
  54730. this._cosYaw = Math.cos(this._halfyaw);
  54731. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  54732. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  54733. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  54734. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  54735. };
  54736. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  54737. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  54738. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  54739. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  54740. this._rotMatrix.m[3] = 0;
  54741. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  54742. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  54743. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  54744. this._rotMatrix.m[7] = 0;
  54745. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  54746. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  54747. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  54748. this._rotMatrix.m[11] = 0;
  54749. this._rotMatrix.m[12] = 0;
  54750. this._rotMatrix.m[13] = 0;
  54751. this._rotMatrix.m[14] = 0;
  54752. this._rotMatrix.m[15] = 1.0;
  54753. };
  54754. /**
  54755. * Disposes the SPS.
  54756. */
  54757. SolidParticleSystem.prototype.dispose = function () {
  54758. this.mesh.dispose();
  54759. this.vars = null;
  54760. // drop references to internal big arrays for the GC
  54761. this._positions = null;
  54762. this._indices = null;
  54763. this._normals = null;
  54764. this._uvs = null;
  54765. this._colors = null;
  54766. this._indices32 = null;
  54767. this._positions32 = null;
  54768. this._normals32 = null;
  54769. this._fixedNormal32 = null;
  54770. this._uvs32 = null;
  54771. this._colors32 = null;
  54772. this.pickedParticles = null;
  54773. };
  54774. /**
  54775. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  54776. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54777. * @returns the SPS.
  54778. */
  54779. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  54780. if (!this._isVisibilityBoxLocked) {
  54781. this.mesh.refreshBoundingInfo();
  54782. }
  54783. return this;
  54784. };
  54785. /**
  54786. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  54787. * @param size the size (float) of the visibility box
  54788. * note : this doesn't lock the SPS mesh bounding box.
  54789. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54790. */
  54791. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  54792. var vis = size / 2;
  54793. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  54794. };
  54795. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  54796. /**
  54797. * Gets whether the SPS as always visible or not
  54798. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54799. */
  54800. get: function () {
  54801. return this._alwaysVisible;
  54802. },
  54803. /**
  54804. * Sets the SPS as always visible or not
  54805. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54806. */
  54807. set: function (val) {
  54808. this._alwaysVisible = val;
  54809. this.mesh.alwaysSelectAsActiveMesh = val;
  54810. },
  54811. enumerable: true,
  54812. configurable: true
  54813. });
  54814. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  54815. /**
  54816. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  54817. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54818. */
  54819. get: function () {
  54820. return this._isVisibilityBoxLocked;
  54821. },
  54822. /**
  54823. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  54824. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  54825. */
  54826. set: function (val) {
  54827. this._isVisibilityBoxLocked = val;
  54828. var boundingInfo = this.mesh.getBoundingInfo();
  54829. boundingInfo.isLocked = val;
  54830. },
  54831. enumerable: true,
  54832. configurable: true
  54833. });
  54834. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  54835. /**
  54836. * Gets if `setParticles()` computes the particle rotations or not.
  54837. * Default value : true. The SPS is faster when it's set to false.
  54838. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  54839. */
  54840. get: function () {
  54841. return this._computeParticleRotation;
  54842. },
  54843. /**
  54844. * Tells to `setParticles()` to compute the particle rotations or not.
  54845. * Default value : true. The SPS is faster when it's set to false.
  54846. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  54847. */
  54848. set: function (val) {
  54849. this._computeParticleRotation = val;
  54850. },
  54851. enumerable: true,
  54852. configurable: true
  54853. });
  54854. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  54855. /**
  54856. * Gets if `setParticles()` computes the particle colors or not.
  54857. * Default value : true. The SPS is faster when it's set to false.
  54858. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  54859. */
  54860. get: function () {
  54861. return this._computeParticleColor;
  54862. },
  54863. /**
  54864. * Tells to `setParticles()` to compute the particle colors or not.
  54865. * Default value : true. The SPS is faster when it's set to false.
  54866. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  54867. */
  54868. set: function (val) {
  54869. this._computeParticleColor = val;
  54870. },
  54871. enumerable: true,
  54872. configurable: true
  54873. });
  54874. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  54875. /**
  54876. * Gets if `setParticles()` computes the particle textures or not.
  54877. * Default value : true. The SPS is faster when it's set to false.
  54878. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  54879. */
  54880. get: function () {
  54881. return this._computeParticleTexture;
  54882. },
  54883. set: function (val) {
  54884. this._computeParticleTexture = val;
  54885. },
  54886. enumerable: true,
  54887. configurable: true
  54888. });
  54889. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  54890. /**
  54891. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  54892. * Default value : false. The SPS is faster when it's set to false.
  54893. * Note : the particle custom vertex positions aren't stored values.
  54894. */
  54895. get: function () {
  54896. return this._computeParticleVertex;
  54897. },
  54898. /**
  54899. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  54900. * Default value : false. The SPS is faster when it's set to false.
  54901. * Note : the particle custom vertex positions aren't stored values.
  54902. */
  54903. set: function (val) {
  54904. this._computeParticleVertex = val;
  54905. },
  54906. enumerable: true,
  54907. configurable: true
  54908. });
  54909. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  54910. /**
  54911. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  54912. */
  54913. get: function () {
  54914. return this._computeBoundingBox;
  54915. },
  54916. /**
  54917. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  54918. */
  54919. set: function (val) {
  54920. this._computeBoundingBox = val;
  54921. },
  54922. enumerable: true,
  54923. configurable: true
  54924. });
  54925. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  54926. /**
  54927. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  54928. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  54929. * Default : `true`
  54930. */
  54931. get: function () {
  54932. return this._depthSortParticles;
  54933. },
  54934. /**
  54935. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  54936. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  54937. * Default : `true`
  54938. */
  54939. set: function (val) {
  54940. this._depthSortParticles = val;
  54941. },
  54942. enumerable: true,
  54943. configurable: true
  54944. });
  54945. // =======================================================================
  54946. // Particle behavior logic
  54947. // these following methods may be overwritten by the user to fit his needs
  54948. /**
  54949. * This function does nothing. It may be overwritten to set all the particle first values.
  54950. * The SPS doesn't call this function, you may have to call it by your own.
  54951. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54952. */
  54953. SolidParticleSystem.prototype.initParticles = function () {
  54954. };
  54955. /**
  54956. * This function does nothing. It may be overwritten to recycle a particle.
  54957. * The SPS doesn't call this function, you may have to call it by your own.
  54958. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54959. * @param particle The particle to recycle
  54960. * @returns the recycled particle
  54961. */
  54962. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  54963. return particle;
  54964. };
  54965. /**
  54966. * Updates a particle : this function should be overwritten by the user.
  54967. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  54968. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  54969. * @example : just set a particle position or velocity and recycle conditions
  54970. * @param particle The particle to update
  54971. * @returns the updated particle
  54972. */
  54973. SolidParticleSystem.prototype.updateParticle = function (particle) {
  54974. return particle;
  54975. };
  54976. /**
  54977. * Updates a vertex of a particle : it can be overwritten by the user.
  54978. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  54979. * @param particle the current particle
  54980. * @param vertex the current index of the current particle
  54981. * @param pt the index of the current vertex in the particle shape
  54982. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  54983. * @example : just set a vertex particle position
  54984. * @returns the updated vertex
  54985. */
  54986. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  54987. return vertex;
  54988. };
  54989. /**
  54990. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  54991. * This does nothing and may be overwritten by the user.
  54992. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54993. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  54994. * @param update the boolean update value actually passed to setParticles()
  54995. */
  54996. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  54997. };
  54998. /**
  54999. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  55000. * This will be passed three parameters.
  55001. * This does nothing and may be overwritten by the user.
  55002. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55003. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  55004. * @param update the boolean update value actually passed to setParticles()
  55005. */
  55006. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  55007. };
  55008. return SolidParticleSystem;
  55009. }());
  55010. BABYLON.SolidParticleSystem = SolidParticleSystem;
  55011. })(BABYLON || (BABYLON = {}));
  55012. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  55013. "use strict";
  55014. var BABYLON;
  55015. (function (BABYLON) {
  55016. var ShaderMaterial = /** @class */ (function (_super) {
  55017. __extends(ShaderMaterial, _super);
  55018. function ShaderMaterial(name, scene, shaderPath, options) {
  55019. var _this = _super.call(this, name, scene) || this;
  55020. _this._textures = {};
  55021. _this._textureArrays = {};
  55022. _this._floats = {};
  55023. _this._ints = {};
  55024. _this._floatsArrays = {};
  55025. _this._colors3 = {};
  55026. _this._colors3Arrays = {};
  55027. _this._colors4 = {};
  55028. _this._vectors2 = {};
  55029. _this._vectors3 = {};
  55030. _this._vectors4 = {};
  55031. _this._matrices = {};
  55032. _this._matrices3x3 = {};
  55033. _this._matrices2x2 = {};
  55034. _this._vectors2Arrays = {};
  55035. _this._vectors3Arrays = {};
  55036. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  55037. _this._shaderPath = shaderPath;
  55038. options.needAlphaBlending = options.needAlphaBlending || false;
  55039. options.needAlphaTesting = options.needAlphaTesting || false;
  55040. options.attributes = options.attributes || ["position", "normal", "uv"];
  55041. options.uniforms = options.uniforms || ["worldViewProjection"];
  55042. options.uniformBuffers = options.uniformBuffers || [];
  55043. options.samplers = options.samplers || [];
  55044. options.defines = options.defines || [];
  55045. _this._options = options;
  55046. return _this;
  55047. }
  55048. ShaderMaterial.prototype.getClassName = function () {
  55049. return "ShaderMaterial";
  55050. };
  55051. ShaderMaterial.prototype.needAlphaBlending = function () {
  55052. return this._options.needAlphaBlending;
  55053. };
  55054. ShaderMaterial.prototype.needAlphaTesting = function () {
  55055. return this._options.needAlphaTesting;
  55056. };
  55057. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  55058. if (this._options.uniforms.indexOf(uniformName) === -1) {
  55059. this._options.uniforms.push(uniformName);
  55060. }
  55061. };
  55062. ShaderMaterial.prototype.setTexture = function (name, texture) {
  55063. if (this._options.samplers.indexOf(name) === -1) {
  55064. this._options.samplers.push(name);
  55065. }
  55066. this._textures[name] = texture;
  55067. return this;
  55068. };
  55069. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  55070. if (this._options.samplers.indexOf(name) === -1) {
  55071. this._options.samplers.push(name);
  55072. }
  55073. this._checkUniform(name);
  55074. this._textureArrays[name] = textures;
  55075. return this;
  55076. };
  55077. ShaderMaterial.prototype.setFloat = function (name, value) {
  55078. this._checkUniform(name);
  55079. this._floats[name] = value;
  55080. return this;
  55081. };
  55082. ShaderMaterial.prototype.setInt = function (name, value) {
  55083. this._checkUniform(name);
  55084. this._ints[name] = value;
  55085. return this;
  55086. };
  55087. ShaderMaterial.prototype.setFloats = function (name, value) {
  55088. this._checkUniform(name);
  55089. this._floatsArrays[name] = value;
  55090. return this;
  55091. };
  55092. ShaderMaterial.prototype.setColor3 = function (name, value) {
  55093. this._checkUniform(name);
  55094. this._colors3[name] = value;
  55095. return this;
  55096. };
  55097. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  55098. this._checkUniform(name);
  55099. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  55100. color.toArray(arr, arr.length);
  55101. return arr;
  55102. }, []);
  55103. return this;
  55104. };
  55105. ShaderMaterial.prototype.setColor4 = function (name, value) {
  55106. this._checkUniform(name);
  55107. this._colors4[name] = value;
  55108. return this;
  55109. };
  55110. ShaderMaterial.prototype.setVector2 = function (name, value) {
  55111. this._checkUniform(name);
  55112. this._vectors2[name] = value;
  55113. return this;
  55114. };
  55115. ShaderMaterial.prototype.setVector3 = function (name, value) {
  55116. this._checkUniform(name);
  55117. this._vectors3[name] = value;
  55118. return this;
  55119. };
  55120. ShaderMaterial.prototype.setVector4 = function (name, value) {
  55121. this._checkUniform(name);
  55122. this._vectors4[name] = value;
  55123. return this;
  55124. };
  55125. ShaderMaterial.prototype.setMatrix = function (name, value) {
  55126. this._checkUniform(name);
  55127. this._matrices[name] = value;
  55128. return this;
  55129. };
  55130. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  55131. this._checkUniform(name);
  55132. this._matrices3x3[name] = value;
  55133. return this;
  55134. };
  55135. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  55136. this._checkUniform(name);
  55137. this._matrices2x2[name] = value;
  55138. return this;
  55139. };
  55140. ShaderMaterial.prototype.setArray2 = function (name, value) {
  55141. this._checkUniform(name);
  55142. this._vectors2Arrays[name] = value;
  55143. return this;
  55144. };
  55145. ShaderMaterial.prototype.setArray3 = function (name, value) {
  55146. this._checkUniform(name);
  55147. this._vectors3Arrays[name] = value;
  55148. return this;
  55149. };
  55150. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  55151. if (!mesh) {
  55152. return true;
  55153. }
  55154. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  55155. return false;
  55156. }
  55157. return false;
  55158. };
  55159. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  55160. var scene = this.getScene();
  55161. var engine = scene.getEngine();
  55162. if (!this.checkReadyOnEveryCall) {
  55163. if (this._renderId === scene.getRenderId()) {
  55164. if (this._checkCache(scene, mesh, useInstances)) {
  55165. return true;
  55166. }
  55167. }
  55168. }
  55169. // Instances
  55170. var defines = [];
  55171. var attribs = [];
  55172. var fallbacks = new BABYLON.EffectFallbacks();
  55173. if (useInstances) {
  55174. defines.push("#define INSTANCES");
  55175. }
  55176. for (var index = 0; index < this._options.defines.length; index++) {
  55177. defines.push(this._options.defines[index]);
  55178. }
  55179. for (var index = 0; index < this._options.attributes.length; index++) {
  55180. attribs.push(this._options.attributes[index]);
  55181. }
  55182. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  55183. attribs.push(BABYLON.VertexBuffer.ColorKind);
  55184. defines.push("#define VERTEXCOLOR");
  55185. }
  55186. // Bones
  55187. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  55188. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  55189. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  55190. if (mesh.numBoneInfluencers > 4) {
  55191. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  55192. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  55193. }
  55194. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  55195. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  55196. fallbacks.addCPUSkinningFallback(0, mesh);
  55197. if (this._options.uniforms.indexOf("mBones") === -1) {
  55198. this._options.uniforms.push("mBones");
  55199. }
  55200. }
  55201. else {
  55202. defines.push("#define NUM_BONE_INFLUENCERS 0");
  55203. }
  55204. // Textures
  55205. for (var name in this._textures) {
  55206. if (!this._textures[name].isReady()) {
  55207. return false;
  55208. }
  55209. }
  55210. // Alpha test
  55211. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  55212. defines.push("#define ALPHATEST");
  55213. }
  55214. var previousEffect = this._effect;
  55215. var join = defines.join("\n");
  55216. this._effect = engine.createEffect(this._shaderPath, {
  55217. attributes: attribs,
  55218. uniformsNames: this._options.uniforms,
  55219. uniformBuffersNames: this._options.uniformBuffers,
  55220. samplers: this._options.samplers,
  55221. defines: join,
  55222. fallbacks: fallbacks,
  55223. onCompiled: this.onCompiled,
  55224. onError: this.onError
  55225. }, engine);
  55226. if (!this._effect.isReady()) {
  55227. return false;
  55228. }
  55229. if (previousEffect !== this._effect) {
  55230. scene.resetCachedMaterial();
  55231. }
  55232. this._renderId = scene.getRenderId();
  55233. return true;
  55234. };
  55235. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  55236. var scene = this.getScene();
  55237. if (!this._effect) {
  55238. return;
  55239. }
  55240. if (this._options.uniforms.indexOf("world") !== -1) {
  55241. this._effect.setMatrix("world", world);
  55242. }
  55243. if (this._options.uniforms.indexOf("worldView") !== -1) {
  55244. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  55245. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  55246. }
  55247. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  55248. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  55249. }
  55250. };
  55251. ShaderMaterial.prototype.bind = function (world, mesh) {
  55252. // Std values
  55253. this.bindOnlyWorldMatrix(world);
  55254. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  55255. if (this._options.uniforms.indexOf("view") !== -1) {
  55256. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  55257. }
  55258. if (this._options.uniforms.indexOf("projection") !== -1) {
  55259. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  55260. }
  55261. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  55262. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  55263. }
  55264. // Bones
  55265. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  55266. var name;
  55267. // Texture
  55268. for (name in this._textures) {
  55269. this._effect.setTexture(name, this._textures[name]);
  55270. }
  55271. // Texture arrays
  55272. for (name in this._textureArrays) {
  55273. this._effect.setTextureArray(name, this._textureArrays[name]);
  55274. }
  55275. // Int
  55276. for (name in this._ints) {
  55277. this._effect.setInt(name, this._ints[name]);
  55278. }
  55279. // Float
  55280. for (name in this._floats) {
  55281. this._effect.setFloat(name, this._floats[name]);
  55282. }
  55283. // Floats
  55284. for (name in this._floatsArrays) {
  55285. this._effect.setArray(name, this._floatsArrays[name]);
  55286. }
  55287. // Color3
  55288. for (name in this._colors3) {
  55289. this._effect.setColor3(name, this._colors3[name]);
  55290. }
  55291. for (name in this._colors3Arrays) {
  55292. this._effect.setArray3(name, this._colors3Arrays[name]);
  55293. }
  55294. // Color4
  55295. for (name in this._colors4) {
  55296. var color = this._colors4[name];
  55297. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  55298. }
  55299. // Vector2
  55300. for (name in this._vectors2) {
  55301. this._effect.setVector2(name, this._vectors2[name]);
  55302. }
  55303. // Vector3
  55304. for (name in this._vectors3) {
  55305. this._effect.setVector3(name, this._vectors3[name]);
  55306. }
  55307. // Vector4
  55308. for (name in this._vectors4) {
  55309. this._effect.setVector4(name, this._vectors4[name]);
  55310. }
  55311. // Matrix
  55312. for (name in this._matrices) {
  55313. this._effect.setMatrix(name, this._matrices[name]);
  55314. }
  55315. // Matrix 3x3
  55316. for (name in this._matrices3x3) {
  55317. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  55318. }
  55319. // Matrix 2x2
  55320. for (name in this._matrices2x2) {
  55321. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  55322. }
  55323. // Vector2Array
  55324. for (name in this._vectors2Arrays) {
  55325. this._effect.setArray2(name, this._vectors2Arrays[name]);
  55326. }
  55327. // Vector3Array
  55328. for (name in this._vectors3Arrays) {
  55329. this._effect.setArray3(name, this._vectors3Arrays[name]);
  55330. }
  55331. }
  55332. this._afterBind(mesh);
  55333. };
  55334. ShaderMaterial.prototype.getActiveTextures = function () {
  55335. var activeTextures = _super.prototype.getActiveTextures.call(this);
  55336. for (var name in this._textures) {
  55337. activeTextures.push(this._textures[name]);
  55338. }
  55339. for (var name in this._textureArrays) {
  55340. var array = this._textureArrays[name];
  55341. for (var index = 0; index < array.length; index++) {
  55342. activeTextures.push(array[index]);
  55343. }
  55344. }
  55345. return activeTextures;
  55346. };
  55347. ShaderMaterial.prototype.hasTexture = function (texture) {
  55348. if (_super.prototype.hasTexture.call(this, texture)) {
  55349. return true;
  55350. }
  55351. for (var name in this._textures) {
  55352. if (this._textures[name] === texture) {
  55353. return true;
  55354. }
  55355. }
  55356. for (var name in this._textureArrays) {
  55357. var array = this._textureArrays[name];
  55358. for (var index = 0; index < array.length; index++) {
  55359. if (array[index] === texture) {
  55360. return true;
  55361. }
  55362. }
  55363. }
  55364. return false;
  55365. };
  55366. ShaderMaterial.prototype.clone = function (name) {
  55367. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  55368. return newShaderMaterial;
  55369. };
  55370. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  55371. if (forceDisposeTextures) {
  55372. var name;
  55373. for (name in this._textures) {
  55374. this._textures[name].dispose();
  55375. }
  55376. for (name in this._textureArrays) {
  55377. var array = this._textureArrays[name];
  55378. for (var index = 0; index < array.length; index++) {
  55379. array[index].dispose();
  55380. }
  55381. }
  55382. }
  55383. this._textures = {};
  55384. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  55385. };
  55386. ShaderMaterial.prototype.serialize = function () {
  55387. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  55388. serializationObject.customType = "BABYLON.ShaderMaterial";
  55389. serializationObject.options = this._options;
  55390. serializationObject.shaderPath = this._shaderPath;
  55391. var name;
  55392. // Texture
  55393. serializationObject.textures = {};
  55394. for (name in this._textures) {
  55395. serializationObject.textures[name] = this._textures[name].serialize();
  55396. }
  55397. // Texture arrays
  55398. serializationObject.textureArrays = {};
  55399. for (name in this._textureArrays) {
  55400. serializationObject.textureArrays[name] = [];
  55401. var array = this._textureArrays[name];
  55402. for (var index = 0; index < array.length; index++) {
  55403. serializationObject.textureArrays[name].push(array[index].serialize());
  55404. }
  55405. }
  55406. // Float
  55407. serializationObject.floats = {};
  55408. for (name in this._floats) {
  55409. serializationObject.floats[name] = this._floats[name];
  55410. }
  55411. // Float s
  55412. serializationObject.FloatArrays = {};
  55413. for (name in this._floatsArrays) {
  55414. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  55415. }
  55416. // Color3
  55417. serializationObject.colors3 = {};
  55418. for (name in this._colors3) {
  55419. serializationObject.colors3[name] = this._colors3[name].asArray();
  55420. }
  55421. // Color3 array
  55422. serializationObject.colors3Arrays = {};
  55423. for (name in this._colors3Arrays) {
  55424. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  55425. }
  55426. // Color4
  55427. serializationObject.colors4 = {};
  55428. for (name in this._colors4) {
  55429. serializationObject.colors4[name] = this._colors4[name].asArray();
  55430. }
  55431. // Vector2
  55432. serializationObject.vectors2 = {};
  55433. for (name in this._vectors2) {
  55434. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  55435. }
  55436. // Vector3
  55437. serializationObject.vectors3 = {};
  55438. for (name in this._vectors3) {
  55439. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  55440. }
  55441. // Vector4
  55442. serializationObject.vectors4 = {};
  55443. for (name in this._vectors4) {
  55444. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  55445. }
  55446. // Matrix
  55447. serializationObject.matrices = {};
  55448. for (name in this._matrices) {
  55449. serializationObject.matrices[name] = this._matrices[name].asArray();
  55450. }
  55451. // Matrix 3x3
  55452. serializationObject.matrices3x3 = {};
  55453. for (name in this._matrices3x3) {
  55454. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  55455. }
  55456. // Matrix 2x2
  55457. serializationObject.matrices2x2 = {};
  55458. for (name in this._matrices2x2) {
  55459. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  55460. }
  55461. // Vector2Array
  55462. serializationObject.vectors2Arrays = {};
  55463. for (name in this._vectors2Arrays) {
  55464. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  55465. }
  55466. // Vector3Array
  55467. serializationObject.vectors3Arrays = {};
  55468. for (name in this._vectors3Arrays) {
  55469. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  55470. }
  55471. return serializationObject;
  55472. };
  55473. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  55474. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  55475. var name;
  55476. // Texture
  55477. for (name in source.textures) {
  55478. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  55479. }
  55480. // Texture arrays
  55481. for (name in source.textureArrays) {
  55482. var array = source.textureArrays[name];
  55483. var textureArray = new Array();
  55484. for (var index = 0; index < array.length; index++) {
  55485. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  55486. }
  55487. material.setTextureArray(name, textureArray);
  55488. }
  55489. // Float
  55490. for (name in source.floats) {
  55491. material.setFloat(name, source.floats[name]);
  55492. }
  55493. // Float s
  55494. for (name in source.floatsArrays) {
  55495. material.setFloats(name, source.floatsArrays[name]);
  55496. }
  55497. // Color3
  55498. for (name in source.colors3) {
  55499. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  55500. }
  55501. // Color3 arrays
  55502. for (name in source.colors3Arrays) {
  55503. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  55504. if (i % 3 === 0) {
  55505. arr.push([num]);
  55506. }
  55507. else {
  55508. arr[arr.length - 1].push(num);
  55509. }
  55510. return arr;
  55511. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  55512. material.setColor3Array(name, colors);
  55513. }
  55514. // Color4
  55515. for (name in source.colors4) {
  55516. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  55517. }
  55518. // Vector2
  55519. for (name in source.vectors2) {
  55520. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  55521. }
  55522. // Vector3
  55523. for (name in source.vectors3) {
  55524. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  55525. }
  55526. // Vector4
  55527. for (name in source.vectors4) {
  55528. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  55529. }
  55530. // Matrix
  55531. for (name in source.matrices) {
  55532. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  55533. }
  55534. // Matrix 3x3
  55535. for (name in source.matrices3x3) {
  55536. material.setMatrix3x3(name, source.matrices3x3[name]);
  55537. }
  55538. // Matrix 2x2
  55539. for (name in source.matrices2x2) {
  55540. material.setMatrix2x2(name, source.matrices2x2[name]);
  55541. }
  55542. // Vector2Array
  55543. for (name in source.vectors2Arrays) {
  55544. material.setArray2(name, source.vectors2Arrays[name]);
  55545. }
  55546. // Vector3Array
  55547. for (name in source.vectors3Arrays) {
  55548. material.setArray3(name, source.vectors3Arrays[name]);
  55549. }
  55550. return material;
  55551. };
  55552. return ShaderMaterial;
  55553. }(BABYLON.Material));
  55554. BABYLON.ShaderMaterial = ShaderMaterial;
  55555. })(BABYLON || (BABYLON = {}));
  55556. //# sourceMappingURL=babylon.shaderMaterial.js.map
  55557. "use strict";
  55558. var BABYLON;
  55559. (function (BABYLON) {
  55560. var GroundMesh = /** @class */ (function (_super) {
  55561. __extends(GroundMesh, _super);
  55562. function GroundMesh(name, scene) {
  55563. var _this = _super.call(this, name, scene) || this;
  55564. _this.generateOctree = false;
  55565. return _this;
  55566. }
  55567. GroundMesh.prototype.getClassName = function () {
  55568. return "GroundMesh";
  55569. };
  55570. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  55571. get: function () {
  55572. return Math.min(this._subdivisionsX, this._subdivisionsY);
  55573. },
  55574. enumerable: true,
  55575. configurable: true
  55576. });
  55577. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  55578. get: function () {
  55579. return this._subdivisionsX;
  55580. },
  55581. enumerable: true,
  55582. configurable: true
  55583. });
  55584. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  55585. get: function () {
  55586. return this._subdivisionsY;
  55587. },
  55588. enumerable: true,
  55589. configurable: true
  55590. });
  55591. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  55592. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  55593. this._subdivisionsX = chunksCount;
  55594. this._subdivisionsY = chunksCount;
  55595. this.subdivide(chunksCount);
  55596. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  55597. };
  55598. /**
  55599. * Returns a height (y) value in the Worl system :
  55600. * the ground altitude at the coordinates (x, z) expressed in the World system.
  55601. * Returns the ground y position if (x, z) are outside the ground surface.
  55602. */
  55603. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  55604. var world = this.getWorldMatrix();
  55605. var invMat = BABYLON.Tmp.Matrix[5];
  55606. world.invertToRef(invMat);
  55607. var tmpVect = BABYLON.Tmp.Vector3[8];
  55608. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  55609. x = tmpVect.x;
  55610. z = tmpVect.z;
  55611. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  55612. return this.position.y;
  55613. }
  55614. if (!this._heightQuads || this._heightQuads.length == 0) {
  55615. this._initHeightQuads();
  55616. this._computeHeightQuads();
  55617. }
  55618. var facet = this._getFacetAt(x, z);
  55619. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  55620. // return y in the World system
  55621. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  55622. return tmpVect.y;
  55623. };
  55624. /**
  55625. * Returns a normalized vector (Vector3) orthogonal to the ground
  55626. * at the ground coordinates (x, z) expressed in the World system.
  55627. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  55628. */
  55629. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  55630. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  55631. this.getNormalAtCoordinatesToRef(x, z, normal);
  55632. return normal;
  55633. };
  55634. /**
  55635. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  55636. * at the ground coordinates (x, z) expressed in the World system.
  55637. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  55638. * Returns the GroundMesh.
  55639. */
  55640. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  55641. var world = this.getWorldMatrix();
  55642. var tmpMat = BABYLON.Tmp.Matrix[5];
  55643. world.invertToRef(tmpMat);
  55644. var tmpVect = BABYLON.Tmp.Vector3[8];
  55645. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  55646. x = tmpVect.x;
  55647. z = tmpVect.z;
  55648. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  55649. return this;
  55650. }
  55651. if (!this._heightQuads || this._heightQuads.length == 0) {
  55652. this._initHeightQuads();
  55653. this._computeHeightQuads();
  55654. }
  55655. var facet = this._getFacetAt(x, z);
  55656. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  55657. return this;
  55658. };
  55659. /**
  55660. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  55661. * if the ground has been updated.
  55662. * This can be used in the render loop.
  55663. * Returns the GroundMesh.
  55664. */
  55665. GroundMesh.prototype.updateCoordinateHeights = function () {
  55666. if (!this._heightQuads || this._heightQuads.length == 0) {
  55667. this._initHeightQuads();
  55668. }
  55669. this._computeHeightQuads();
  55670. return this;
  55671. };
  55672. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  55673. GroundMesh.prototype._getFacetAt = function (x, z) {
  55674. // retrieve col and row from x, z coordinates in the ground local system
  55675. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  55676. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  55677. var quad = this._heightQuads[row * this._subdivisionsX + col];
  55678. var facet;
  55679. if (z < quad.slope.x * x + quad.slope.y) {
  55680. facet = quad.facet1;
  55681. }
  55682. else {
  55683. facet = quad.facet2;
  55684. }
  55685. return facet;
  55686. };
  55687. // Creates and populates the heightMap array with "facet" elements :
  55688. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  55689. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  55690. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  55691. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  55692. // Returns the GroundMesh.
  55693. GroundMesh.prototype._initHeightQuads = function () {
  55694. var subdivisionsX = this._subdivisionsX;
  55695. var subdivisionsY = this._subdivisionsY;
  55696. this._heightQuads = new Array();
  55697. for (var row = 0; row < subdivisionsY; row++) {
  55698. for (var col = 0; col < subdivisionsX; col++) {
  55699. 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) };
  55700. this._heightQuads[row * subdivisionsX + col] = quad;
  55701. }
  55702. }
  55703. return this;
  55704. };
  55705. // Compute each quad element values and update the the heightMap array :
  55706. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  55707. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  55708. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  55709. // Returns the GroundMesh.
  55710. GroundMesh.prototype._computeHeightQuads = function () {
  55711. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  55712. if (!positions) {
  55713. return this;
  55714. }
  55715. var v1 = BABYLON.Tmp.Vector3[3];
  55716. var v2 = BABYLON.Tmp.Vector3[2];
  55717. var v3 = BABYLON.Tmp.Vector3[1];
  55718. var v4 = BABYLON.Tmp.Vector3[0];
  55719. var v1v2 = BABYLON.Tmp.Vector3[4];
  55720. var v1v3 = BABYLON.Tmp.Vector3[5];
  55721. var v1v4 = BABYLON.Tmp.Vector3[6];
  55722. var norm1 = BABYLON.Tmp.Vector3[7];
  55723. var norm2 = BABYLON.Tmp.Vector3[8];
  55724. var i = 0;
  55725. var j = 0;
  55726. var k = 0;
  55727. var cd = 0; // 2D slope coefficient : z = cd * x + h
  55728. var h = 0;
  55729. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  55730. var d2 = 0;
  55731. var subdivisionsX = this._subdivisionsX;
  55732. var subdivisionsY = this._subdivisionsY;
  55733. for (var row = 0; row < subdivisionsY; row++) {
  55734. for (var col = 0; col < subdivisionsX; col++) {
  55735. i = col * 3;
  55736. j = row * (subdivisionsX + 1) * 3;
  55737. k = (row + 1) * (subdivisionsX + 1) * 3;
  55738. v1.x = positions[j + i];
  55739. v1.y = positions[j + i + 1];
  55740. v1.z = positions[j + i + 2];
  55741. v2.x = positions[j + i + 3];
  55742. v2.y = positions[j + i + 4];
  55743. v2.z = positions[j + i + 5];
  55744. v3.x = positions[k + i];
  55745. v3.y = positions[k + i + 1];
  55746. v3.z = positions[k + i + 2];
  55747. v4.x = positions[k + i + 3];
  55748. v4.y = positions[k + i + 4];
  55749. v4.z = positions[k + i + 5];
  55750. // 2D slope V1V4
  55751. cd = (v4.z - v1.z) / (v4.x - v1.x);
  55752. h = v1.z - cd * v1.x; // v1 belongs to the slope
  55753. // facet equations :
  55754. // we compute each facet normal vector
  55755. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  55756. // we compute the value d by applying the equation to v1 which belongs to the plane
  55757. // then we store the facet equation in a Vector4
  55758. v2.subtractToRef(v1, v1v2);
  55759. v3.subtractToRef(v1, v1v3);
  55760. v4.subtractToRef(v1, v1v4);
  55761. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  55762. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  55763. norm1.normalize();
  55764. norm2.normalize();
  55765. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  55766. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  55767. var quad = this._heightQuads[row * subdivisionsX + col];
  55768. quad.slope.copyFromFloats(cd, h);
  55769. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  55770. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  55771. }
  55772. }
  55773. return this;
  55774. };
  55775. GroundMesh.prototype.serialize = function (serializationObject) {
  55776. _super.prototype.serialize.call(this, serializationObject);
  55777. serializationObject.subdivisionsX = this._subdivisionsX;
  55778. serializationObject.subdivisionsY = this._subdivisionsY;
  55779. serializationObject.minX = this._minX;
  55780. serializationObject.maxX = this._maxX;
  55781. serializationObject.minZ = this._minZ;
  55782. serializationObject.maxZ = this._maxZ;
  55783. serializationObject.width = this._width;
  55784. serializationObject.height = this._height;
  55785. };
  55786. GroundMesh.Parse = function (parsedMesh, scene) {
  55787. var result = new GroundMesh(parsedMesh.name, scene);
  55788. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  55789. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  55790. result._minX = parsedMesh.minX;
  55791. result._maxX = parsedMesh.maxX;
  55792. result._minZ = parsedMesh.minZ;
  55793. result._maxZ = parsedMesh.maxZ;
  55794. result._width = parsedMesh.width;
  55795. result._height = parsedMesh.height;
  55796. return result;
  55797. };
  55798. return GroundMesh;
  55799. }(BABYLON.Mesh));
  55800. BABYLON.GroundMesh = GroundMesh;
  55801. })(BABYLON || (BABYLON = {}));
  55802. //# sourceMappingURL=babylon.groundMesh.js.map
  55803. "use strict";
  55804. var BABYLON;
  55805. (function (BABYLON) {
  55806. /**
  55807. * Creates an instance based on a source mesh.
  55808. */
  55809. var InstancedMesh = /** @class */ (function (_super) {
  55810. __extends(InstancedMesh, _super);
  55811. function InstancedMesh(name, source) {
  55812. var _this = _super.call(this, name, source.getScene()) || this;
  55813. source.instances.push(_this);
  55814. _this._sourceMesh = source;
  55815. _this.position.copyFrom(source.position);
  55816. _this.rotation.copyFrom(source.rotation);
  55817. _this.scaling.copyFrom(source.scaling);
  55818. if (source.rotationQuaternion) {
  55819. _this.rotationQuaternion = source.rotationQuaternion.clone();
  55820. }
  55821. _this.infiniteDistance = source.infiniteDistance;
  55822. _this.setPivotMatrix(source.getPivotMatrix());
  55823. _this.refreshBoundingInfo();
  55824. _this._syncSubMeshes();
  55825. return _this;
  55826. }
  55827. /**
  55828. * Returns the string "InstancedMesh".
  55829. */
  55830. InstancedMesh.prototype.getClassName = function () {
  55831. return "InstancedMesh";
  55832. };
  55833. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  55834. // Methods
  55835. get: function () {
  55836. return this._sourceMesh.receiveShadows;
  55837. },
  55838. enumerable: true,
  55839. configurable: true
  55840. });
  55841. Object.defineProperty(InstancedMesh.prototype, "material", {
  55842. get: function () {
  55843. return this._sourceMesh.material;
  55844. },
  55845. enumerable: true,
  55846. configurable: true
  55847. });
  55848. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  55849. get: function () {
  55850. return this._sourceMesh.visibility;
  55851. },
  55852. enumerable: true,
  55853. configurable: true
  55854. });
  55855. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  55856. get: function () {
  55857. return this._sourceMesh.skeleton;
  55858. },
  55859. enumerable: true,
  55860. configurable: true
  55861. });
  55862. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  55863. get: function () {
  55864. return this._sourceMesh.renderingGroupId;
  55865. },
  55866. set: function (value) {
  55867. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  55868. return;
  55869. }
  55870. //no-op with warning
  55871. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  55872. },
  55873. enumerable: true,
  55874. configurable: true
  55875. });
  55876. /**
  55877. * Returns the total number of vertices (integer).
  55878. */
  55879. InstancedMesh.prototype.getTotalVertices = function () {
  55880. return this._sourceMesh.getTotalVertices();
  55881. };
  55882. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  55883. get: function () {
  55884. return this._sourceMesh;
  55885. },
  55886. enumerable: true,
  55887. configurable: true
  55888. });
  55889. /**
  55890. * Is this node ready to be used/rendered
  55891. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  55892. * @return {boolean} is it ready
  55893. */
  55894. InstancedMesh.prototype.isReady = function (completeCheck) {
  55895. if (completeCheck === void 0) { completeCheck = false; }
  55896. return this._sourceMesh.isReady(completeCheck, true);
  55897. };
  55898. /**
  55899. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  55900. */
  55901. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  55902. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  55903. };
  55904. /**
  55905. * Sets the vertex data of the mesh geometry for the requested `kind`.
  55906. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  55907. * The `data` are either a numeric array either a Float32Array.
  55908. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  55909. * 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).
  55910. * Note that a new underlying VertexBuffer object is created each call.
  55911. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  55912. *
  55913. * Possible `kind` values :
  55914. * - BABYLON.VertexBuffer.PositionKind
  55915. * - BABYLON.VertexBuffer.UVKind
  55916. * - BABYLON.VertexBuffer.UV2Kind
  55917. * - BABYLON.VertexBuffer.UV3Kind
  55918. * - BABYLON.VertexBuffer.UV4Kind
  55919. * - BABYLON.VertexBuffer.UV5Kind
  55920. * - BABYLON.VertexBuffer.UV6Kind
  55921. * - BABYLON.VertexBuffer.ColorKind
  55922. * - BABYLON.VertexBuffer.MatricesIndicesKind
  55923. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  55924. * - BABYLON.VertexBuffer.MatricesWeightsKind
  55925. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  55926. *
  55927. * Returns the Mesh.
  55928. */
  55929. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  55930. if (this.sourceMesh) {
  55931. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  55932. }
  55933. return this.sourceMesh;
  55934. };
  55935. /**
  55936. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  55937. * If the mesh has no geometry, it is simply returned as it is.
  55938. * The `data` are either a numeric array either a Float32Array.
  55939. * No new underlying VertexBuffer object is created.
  55940. * 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.
  55941. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  55942. *
  55943. * Possible `kind` values :
  55944. * - BABYLON.VertexBuffer.PositionKind
  55945. * - BABYLON.VertexBuffer.UVKind
  55946. * - BABYLON.VertexBuffer.UV2Kind
  55947. * - BABYLON.VertexBuffer.UV3Kind
  55948. * - BABYLON.VertexBuffer.UV4Kind
  55949. * - BABYLON.VertexBuffer.UV5Kind
  55950. * - BABYLON.VertexBuffer.UV6Kind
  55951. * - BABYLON.VertexBuffer.ColorKind
  55952. * - BABYLON.VertexBuffer.MatricesIndicesKind
  55953. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  55954. * - BABYLON.VertexBuffer.MatricesWeightsKind
  55955. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  55956. *
  55957. * Returns the Mesh.
  55958. */
  55959. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  55960. if (this.sourceMesh) {
  55961. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  55962. }
  55963. return this.sourceMesh;
  55964. };
  55965. /**
  55966. * Sets the mesh indices.
  55967. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  55968. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  55969. * This method creates a new index buffer each call.
  55970. * Returns the Mesh.
  55971. */
  55972. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  55973. if (totalVertices === void 0) { totalVertices = null; }
  55974. if (this.sourceMesh) {
  55975. this.sourceMesh.setIndices(indices, totalVertices);
  55976. }
  55977. return this.sourceMesh;
  55978. };
  55979. /**
  55980. * Boolean : True if the mesh owns the requested kind of data.
  55981. */
  55982. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  55983. return this._sourceMesh.isVerticesDataPresent(kind);
  55984. };
  55985. /**
  55986. * Returns an array of indices (IndicesArray).
  55987. */
  55988. InstancedMesh.prototype.getIndices = function () {
  55989. return this._sourceMesh.getIndices();
  55990. };
  55991. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  55992. get: function () {
  55993. return this._sourceMesh._positions;
  55994. },
  55995. enumerable: true,
  55996. configurable: true
  55997. });
  55998. /**
  55999. * Sets a new updated BoundingInfo to the mesh.
  56000. * Returns the mesh.
  56001. */
  56002. InstancedMesh.prototype.refreshBoundingInfo = function () {
  56003. var meshBB = this._sourceMesh.getBoundingInfo();
  56004. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  56005. this._updateBoundingInfo();
  56006. return this;
  56007. };
  56008. InstancedMesh.prototype._preActivate = function () {
  56009. if (this._currentLOD) {
  56010. this._currentLOD._preActivate();
  56011. }
  56012. return this;
  56013. };
  56014. InstancedMesh.prototype._activate = function (renderId) {
  56015. if (this._currentLOD) {
  56016. this._currentLOD._registerInstanceForRenderId(this, renderId);
  56017. }
  56018. return this;
  56019. };
  56020. /**
  56021. * Returns the current associated LOD AbstractMesh.
  56022. */
  56023. InstancedMesh.prototype.getLOD = function (camera) {
  56024. if (!camera) {
  56025. return this;
  56026. }
  56027. var boundingInfo = this.getBoundingInfo();
  56028. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  56029. if (this._currentLOD === this.sourceMesh) {
  56030. return this;
  56031. }
  56032. return this._currentLOD;
  56033. };
  56034. InstancedMesh.prototype._syncSubMeshes = function () {
  56035. this.releaseSubMeshes();
  56036. if (this._sourceMesh.subMeshes) {
  56037. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  56038. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  56039. }
  56040. }
  56041. return this;
  56042. };
  56043. InstancedMesh.prototype._generatePointsArray = function () {
  56044. return this._sourceMesh._generatePointsArray();
  56045. };
  56046. /**
  56047. * Creates a new InstancedMesh from the current mesh.
  56048. * - name (string) : the cloned mesh name
  56049. * - newParent (optional Node) : the optional Node to parent the clone to.
  56050. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  56051. *
  56052. * Returns the clone.
  56053. */
  56054. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  56055. var result = this._sourceMesh.createInstance(name);
  56056. // Deep copy
  56057. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  56058. // Bounding info
  56059. this.refreshBoundingInfo();
  56060. // Parent
  56061. if (newParent) {
  56062. result.parent = newParent;
  56063. }
  56064. if (!doNotCloneChildren) {
  56065. // Children
  56066. for (var index = 0; index < this.getScene().meshes.length; index++) {
  56067. var mesh = this.getScene().meshes[index];
  56068. if (mesh.parent === this) {
  56069. mesh.clone(mesh.name, result);
  56070. }
  56071. }
  56072. }
  56073. result.computeWorldMatrix(true);
  56074. return result;
  56075. };
  56076. /**
  56077. * Disposes the InstancedMesh.
  56078. * Returns nothing.
  56079. */
  56080. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  56081. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  56082. // Remove from mesh
  56083. var index = this._sourceMesh.instances.indexOf(this);
  56084. this._sourceMesh.instances.splice(index, 1);
  56085. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  56086. };
  56087. return InstancedMesh;
  56088. }(BABYLON.AbstractMesh));
  56089. BABYLON.InstancedMesh = InstancedMesh;
  56090. })(BABYLON || (BABYLON = {}));
  56091. //# sourceMappingURL=babylon.instancedMesh.js.map
  56092. "use strict";
  56093. var BABYLON;
  56094. (function (BABYLON) {
  56095. var LinesMesh = /** @class */ (function (_super) {
  56096. __extends(LinesMesh, _super);
  56097. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  56098. if (scene === void 0) { scene = null; }
  56099. if (parent === void 0) { parent = null; }
  56100. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  56101. _this.useVertexColor = useVertexColor;
  56102. _this.useVertexAlpha = useVertexAlpha;
  56103. _this.color = new BABYLON.Color3(1, 1, 1);
  56104. _this.alpha = 1;
  56105. if (source) {
  56106. _this.color = source.color.clone();
  56107. _this.alpha = source.alpha;
  56108. _this.useVertexColor = source.useVertexColor;
  56109. _this.useVertexAlpha = source.useVertexAlpha;
  56110. }
  56111. _this._intersectionThreshold = 0.1;
  56112. var defines = [];
  56113. var options = {
  56114. attributes: [BABYLON.VertexBuffer.PositionKind],
  56115. uniforms: ["world", "viewProjection"],
  56116. needAlphaBlending: true,
  56117. defines: defines
  56118. };
  56119. if (useVertexAlpha === false) {
  56120. options.needAlphaBlending = false;
  56121. }
  56122. if (!useVertexColor) {
  56123. options.uniforms.push("color");
  56124. }
  56125. else {
  56126. options.defines.push("#define VERTEXCOLOR");
  56127. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  56128. }
  56129. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  56130. return _this;
  56131. }
  56132. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  56133. /**
  56134. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  56135. * This margin is expressed in world space coordinates, so its value may vary.
  56136. * Default value is 0.1
  56137. * @returns the intersection Threshold value.
  56138. */
  56139. get: function () {
  56140. return this._intersectionThreshold;
  56141. },
  56142. /**
  56143. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  56144. * This margin is expressed in world space coordinates, so its value may vary.
  56145. * @param value the new threshold to apply
  56146. */
  56147. set: function (value) {
  56148. if (this._intersectionThreshold === value) {
  56149. return;
  56150. }
  56151. this._intersectionThreshold = value;
  56152. if (this.geometry) {
  56153. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  56154. }
  56155. },
  56156. enumerable: true,
  56157. configurable: true
  56158. });
  56159. /**
  56160. * Returns the string "LineMesh"
  56161. */
  56162. LinesMesh.prototype.getClassName = function () {
  56163. return "LinesMesh";
  56164. };
  56165. Object.defineProperty(LinesMesh.prototype, "material", {
  56166. get: function () {
  56167. return this._colorShader;
  56168. },
  56169. set: function (value) {
  56170. // Do nothing
  56171. },
  56172. enumerable: true,
  56173. configurable: true
  56174. });
  56175. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  56176. get: function () {
  56177. return false;
  56178. },
  56179. enumerable: true,
  56180. configurable: true
  56181. });
  56182. LinesMesh.prototype.createInstance = function (name) {
  56183. throw new Error("LinesMeshes do not support createInstance.");
  56184. };
  56185. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  56186. if (!this._geometry) {
  56187. return this;
  56188. }
  56189. // VBOs
  56190. this._geometry._bind(this._colorShader.getEffect());
  56191. // Color
  56192. if (!this.useVertexColor) {
  56193. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  56194. }
  56195. return this;
  56196. };
  56197. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  56198. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  56199. return this;
  56200. }
  56201. var engine = this.getScene().getEngine();
  56202. // Draw order
  56203. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  56204. return this;
  56205. };
  56206. LinesMesh.prototype.dispose = function (doNotRecurse) {
  56207. this._colorShader.dispose();
  56208. _super.prototype.dispose.call(this, doNotRecurse);
  56209. };
  56210. /**
  56211. * Returns a new LineMesh object cloned from the current one.
  56212. */
  56213. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  56214. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  56215. };
  56216. return LinesMesh;
  56217. }(BABYLON.Mesh));
  56218. BABYLON.LinesMesh = LinesMesh;
  56219. })(BABYLON || (BABYLON = {}));
  56220. //# sourceMappingURL=babylon.linesMesh.js.map
  56221. "use strict";
  56222. var BABYLON;
  56223. (function (BABYLON) {
  56224. var MeshBuilder = /** @class */ (function () {
  56225. function MeshBuilder() {
  56226. }
  56227. MeshBuilder.updateSideOrientation = function (orientation) {
  56228. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  56229. return BABYLON.Mesh.DOUBLESIDE;
  56230. }
  56231. if (orientation === undefined || orientation === null) {
  56232. return BABYLON.Mesh.FRONTSIDE;
  56233. }
  56234. return orientation;
  56235. };
  56236. /**
  56237. * Creates a box mesh.
  56238. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  56239. * The parameter `size` sets the size (float) of each box side (default 1).
  56240. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  56241. * 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).
  56242. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  56243. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56244. * 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).
  56245. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56246. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56247. */
  56248. MeshBuilder.CreateBox = function (name, options, scene) {
  56249. if (scene === void 0) { scene = null; }
  56250. var box = new BABYLON.Mesh(name, scene);
  56251. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56252. box._originalBuilderSideOrientation = options.sideOrientation;
  56253. var vertexData = BABYLON.VertexData.CreateBox(options);
  56254. vertexData.applyToMesh(box, options.updatable);
  56255. return box;
  56256. };
  56257. /**
  56258. * Creates a sphere mesh.
  56259. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  56260. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  56261. * 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`).
  56262. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  56263. * 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
  56264. * 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).
  56265. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56266. * 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).
  56267. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56268. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56269. */
  56270. MeshBuilder.CreateSphere = function (name, options, scene) {
  56271. var sphere = new BABYLON.Mesh(name, scene);
  56272. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56273. sphere._originalBuilderSideOrientation = options.sideOrientation;
  56274. var vertexData = BABYLON.VertexData.CreateSphere(options);
  56275. vertexData.applyToMesh(sphere, options.updatable);
  56276. return sphere;
  56277. };
  56278. /**
  56279. * Creates a plane polygonal mesh. By default, this is a disc.
  56280. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  56281. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  56282. * 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.
  56283. * 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
  56284. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56285. * 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).
  56286. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56287. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56288. */
  56289. MeshBuilder.CreateDisc = function (name, options, scene) {
  56290. if (scene === void 0) { scene = null; }
  56291. var disc = new BABYLON.Mesh(name, scene);
  56292. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56293. disc._originalBuilderSideOrientation = options.sideOrientation;
  56294. var vertexData = BABYLON.VertexData.CreateDisc(options);
  56295. vertexData.applyToMesh(disc, options.updatable);
  56296. return disc;
  56297. };
  56298. /**
  56299. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  56300. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  56301. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  56302. * 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`).
  56303. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  56304. * 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.
  56305. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56306. * 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).
  56307. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56308. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56309. */
  56310. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  56311. var sphere = new BABYLON.Mesh(name, scene);
  56312. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56313. sphere._originalBuilderSideOrientation = options.sideOrientation;
  56314. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  56315. vertexData.applyToMesh(sphere, options.updatable);
  56316. return sphere;
  56317. };
  56318. ;
  56319. /**
  56320. * Creates a ribbon mesh.
  56321. * 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.
  56322. *
  56323. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  56324. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  56325. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  56326. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  56327. * 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.
  56328. * 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.
  56329. * 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
  56330. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56331. * 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).
  56332. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56333. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56334. * 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.
  56335. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  56336. * 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
  56337. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  56338. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  56339. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56340. */
  56341. MeshBuilder.CreateRibbon = function (name, options, scene) {
  56342. if (scene === void 0) { scene = null; }
  56343. var pathArray = options.pathArray;
  56344. var closeArray = options.closeArray;
  56345. var closePath = options.closePath;
  56346. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56347. var instance = options.instance;
  56348. var updatable = options.updatable;
  56349. if (instance) {
  56350. // positionFunction : ribbon case
  56351. // only pathArray and sideOrientation parameters are taken into account for positions update
  56352. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  56353. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  56354. var positionFunction = function (positions) {
  56355. var minlg = pathArray[0].length;
  56356. var i = 0;
  56357. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  56358. for (var si = 1; si <= ns; si++) {
  56359. for (var p = 0; p < pathArray.length; p++) {
  56360. var path = pathArray[p];
  56361. var l = path.length;
  56362. minlg = (minlg < l) ? minlg : l;
  56363. var j = 0;
  56364. while (j < minlg) {
  56365. positions[i] = path[j].x;
  56366. positions[i + 1] = path[j].y;
  56367. positions[i + 2] = path[j].z;
  56368. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  56369. BABYLON.Tmp.Vector3[0].x = path[j].x;
  56370. }
  56371. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  56372. BABYLON.Tmp.Vector3[1].x = path[j].x;
  56373. }
  56374. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  56375. BABYLON.Tmp.Vector3[0].y = path[j].y;
  56376. }
  56377. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  56378. BABYLON.Tmp.Vector3[1].y = path[j].y;
  56379. }
  56380. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  56381. BABYLON.Tmp.Vector3[0].z = path[j].z;
  56382. }
  56383. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  56384. BABYLON.Tmp.Vector3[1].z = path[j].z;
  56385. }
  56386. j++;
  56387. i += 3;
  56388. }
  56389. if (instance._closePath) {
  56390. positions[i] = path[0].x;
  56391. positions[i + 1] = path[0].y;
  56392. positions[i + 2] = path[0].z;
  56393. i += 3;
  56394. }
  56395. }
  56396. }
  56397. };
  56398. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56399. positionFunction(positions);
  56400. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  56401. instance._boundingInfo.update(instance._worldMatrix);
  56402. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  56403. if (options.colors) {
  56404. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  56405. for (var c = 0; c < options.colors.length; c++) {
  56406. colors[c * 4] = options.colors[c].r;
  56407. colors[c * 4 + 1] = options.colors[c].g;
  56408. colors[c * 4 + 2] = options.colors[c].b;
  56409. colors[c * 4 + 3] = options.colors[c].a;
  56410. }
  56411. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  56412. }
  56413. if (options.uvs) {
  56414. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  56415. for (var i = 0; i < options.uvs.length; i++) {
  56416. uvs[i * 2] = options.uvs[i].x;
  56417. uvs[i * 2 + 1] = options.uvs[i].y;
  56418. }
  56419. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  56420. }
  56421. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  56422. var indices = instance.getIndices();
  56423. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  56424. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  56425. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  56426. if (instance._closePath) {
  56427. var indexFirst = 0;
  56428. var indexLast = 0;
  56429. for (var p = 0; p < pathArray.length; p++) {
  56430. indexFirst = instance._idx[p] * 3;
  56431. if (p + 1 < pathArray.length) {
  56432. indexLast = (instance._idx[p + 1] - 1) * 3;
  56433. }
  56434. else {
  56435. indexLast = normals.length - 3;
  56436. }
  56437. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  56438. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  56439. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  56440. normals[indexLast] = normals[indexFirst];
  56441. normals[indexLast + 1] = normals[indexFirst + 1];
  56442. normals[indexLast + 2] = normals[indexFirst + 2];
  56443. }
  56444. }
  56445. if (!(instance.areNormalsFrozen)) {
  56446. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  56447. }
  56448. }
  56449. return instance;
  56450. }
  56451. else {
  56452. var ribbon = new BABYLON.Mesh(name, scene);
  56453. ribbon._originalBuilderSideOrientation = sideOrientation;
  56454. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  56455. if (closePath) {
  56456. ribbon._idx = vertexData._idx;
  56457. }
  56458. ribbon._closePath = closePath;
  56459. ribbon._closeArray = closeArray;
  56460. vertexData.applyToMesh(ribbon, updatable);
  56461. return ribbon;
  56462. }
  56463. };
  56464. /**
  56465. * Creates a cylinder or a cone mesh.
  56466. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  56467. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  56468. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  56469. * 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.
  56470. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  56471. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  56472. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  56473. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  56474. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  56475. * 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).
  56476. * 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
  56477. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  56478. * 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
  56479. * 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.
  56480. * If `enclose` is false, a ring surface is one element.
  56481. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  56482. * 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
  56483. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56484. * 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).
  56485. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56486. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56487. */
  56488. MeshBuilder.CreateCylinder = function (name, options, scene) {
  56489. var cylinder = new BABYLON.Mesh(name, scene);
  56490. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56491. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  56492. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  56493. vertexData.applyToMesh(cylinder, options.updatable);
  56494. return cylinder;
  56495. };
  56496. /**
  56497. * Creates a torus mesh.
  56498. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  56499. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  56500. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  56501. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  56502. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56503. * 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).
  56504. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56505. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56506. */
  56507. MeshBuilder.CreateTorus = function (name, options, scene) {
  56508. var torus = new BABYLON.Mesh(name, scene);
  56509. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56510. torus._originalBuilderSideOrientation = options.sideOrientation;
  56511. var vertexData = BABYLON.VertexData.CreateTorus(options);
  56512. vertexData.applyToMesh(torus, options.updatable);
  56513. return torus;
  56514. };
  56515. /**
  56516. * Creates a torus knot mesh.
  56517. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  56518. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  56519. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  56520. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  56521. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  56522. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56523. * 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).
  56524. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56525. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56526. */
  56527. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  56528. var torusKnot = new BABYLON.Mesh(name, scene);
  56529. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56530. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  56531. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  56532. vertexData.applyToMesh(torusKnot, options.updatable);
  56533. return torusKnot;
  56534. };
  56535. /**
  56536. * Creates a line system mesh.
  56537. * A line system is a pool of many lines gathered in a single mesh.
  56538. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  56539. * 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.
  56540. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  56541. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  56542. * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter. The way to update it is the same than for
  56543. * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point.
  56544. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need the alpha blending (faster).
  56545. * 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
  56546. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  56547. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56548. */
  56549. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  56550. var instance = options.instance;
  56551. var lines = options.lines;
  56552. var colors = options.colors;
  56553. if (instance) {
  56554. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56555. var vertexColor;
  56556. var lineColors;
  56557. if (colors) {
  56558. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  56559. }
  56560. var i = 0;
  56561. var c = 0;
  56562. for (var l = 0; l < lines.length; l++) {
  56563. var points = lines[l];
  56564. for (var p = 0; p < points.length; p++) {
  56565. positions[i] = points[p].x;
  56566. positions[i + 1] = points[p].y;
  56567. positions[i + 2] = points[p].z;
  56568. if (colors && vertexColor) {
  56569. lineColors = colors[l];
  56570. vertexColor[c] = lineColors[p].r;
  56571. vertexColor[c + 1] = lineColors[p].g;
  56572. vertexColor[c + 2] = lineColors[p].b;
  56573. vertexColor[c + 3] = lineColors[p].a;
  56574. c += 4;
  56575. }
  56576. i += 3;
  56577. }
  56578. }
  56579. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  56580. if (colors && vertexColor) {
  56581. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  56582. }
  56583. return instance;
  56584. }
  56585. // line system creation
  56586. var useVertexColor = (colors) ? true : false;
  56587. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  56588. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  56589. vertexData.applyToMesh(lineSystem, options.updatable);
  56590. return lineSystem;
  56591. };
  56592. /**
  56593. * Creates a line mesh.
  56594. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  56595. * 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.
  56596. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  56597. * The parameter `points` is an array successive Vector3.
  56598. * 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
  56599. * The optional parameter `colors` is an array of successive Color4, one per line point.
  56600. * The optional parameter `useVertexAlpha' is to be set to `false` (default `true`) when you don't need alpha blending (faster).
  56601. * When updating an instance, remember that only point positions can change, not the number of points.
  56602. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56603. */
  56604. MeshBuilder.CreateLines = function (name, options, scene) {
  56605. if (scene === void 0) { scene = null; }
  56606. var colors = (options.colors) ? [options.colors] : null;
  56607. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  56608. return lines;
  56609. };
  56610. /**
  56611. * Creates a dashed line mesh.
  56612. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  56613. * 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.
  56614. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  56615. * The parameter `points` is an array successive Vector3.
  56616. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  56617. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  56618. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  56619. * 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
  56620. * When updating an instance, remember that only point positions can change, not the number of points.
  56621. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56622. */
  56623. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  56624. if (scene === void 0) { scene = null; }
  56625. var points = options.points;
  56626. var instance = options.instance;
  56627. var gapSize = options.gapSize || 1;
  56628. var dashSize = options.dashSize || 3;
  56629. if (instance) {
  56630. var positionFunction = function (positions) {
  56631. var curvect = BABYLON.Vector3.Zero();
  56632. var nbSeg = positions.length / 6;
  56633. var lg = 0;
  56634. var nb = 0;
  56635. var shft = 0;
  56636. var dashshft = 0;
  56637. var curshft = 0;
  56638. var p = 0;
  56639. var i = 0;
  56640. var j = 0;
  56641. for (i = 0; i < points.length - 1; i++) {
  56642. points[i + 1].subtractToRef(points[i], curvect);
  56643. lg += curvect.length();
  56644. }
  56645. shft = lg / nbSeg;
  56646. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  56647. for (i = 0; i < points.length - 1; i++) {
  56648. points[i + 1].subtractToRef(points[i], curvect);
  56649. nb = Math.floor(curvect.length() / shft);
  56650. curvect.normalize();
  56651. j = 0;
  56652. while (j < nb && p < positions.length) {
  56653. curshft = shft * j;
  56654. positions[p] = points[i].x + curshft * curvect.x;
  56655. positions[p + 1] = points[i].y + curshft * curvect.y;
  56656. positions[p + 2] = points[i].z + curshft * curvect.z;
  56657. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  56658. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  56659. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  56660. p += 6;
  56661. j++;
  56662. }
  56663. }
  56664. while (p < positions.length) {
  56665. positions[p] = points[i].x;
  56666. positions[p + 1] = points[i].y;
  56667. positions[p + 2] = points[i].z;
  56668. p += 3;
  56669. }
  56670. };
  56671. instance.updateMeshPositions(positionFunction, false);
  56672. return instance;
  56673. }
  56674. // dashed lines creation
  56675. var dashedLines = new BABYLON.LinesMesh(name, scene);
  56676. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  56677. vertexData.applyToMesh(dashedLines, options.updatable);
  56678. dashedLines.dashSize = dashSize;
  56679. dashedLines.gapSize = gapSize;
  56680. return dashedLines;
  56681. };
  56682. /**
  56683. * Creates an extruded shape mesh.
  56684. * 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.
  56685. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  56686. *
  56687. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  56688. * 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
  56689. * extruded along the Z axis.
  56690. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  56691. * 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.
  56692. * The parameter `scale` (float, default 1) is the value to scale the shape.
  56693. * 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
  56694. * 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
  56695. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  56696. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56697. * 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).
  56698. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56699. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56700. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56701. */
  56702. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  56703. if (scene === void 0) { scene = null; }
  56704. var path = options.path;
  56705. var shape = options.shape;
  56706. var scale = options.scale || 1;
  56707. var rotation = options.rotation || 0;
  56708. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  56709. var updatable = options.updatable;
  56710. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56711. var instance = options.instance || null;
  56712. var invertUV = options.invertUV || false;
  56713. 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);
  56714. };
  56715. /**
  56716. * Creates an custom extruded shape mesh.
  56717. * 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.
  56718. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  56719. *
  56720. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  56721. * 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
  56722. * extruded along the Z axis.
  56723. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  56724. * 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
  56725. * and the distance of this point from the begining of the path :
  56726. * ```javascript
  56727. * var rotationFunction = function(i, distance) {
  56728. * // do things
  56729. * return rotationValue; }
  56730. * ```
  56731. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  56732. * 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
  56733. * and the distance of this point from the begining of the path :
  56734. * ```javascript
  56735. * var scaleFunction = function(i, distance) {
  56736. * // do things
  56737. * return scaleValue;}
  56738. * ```
  56739. * It must returns a float value that will be the scale value applied to the shape on each path point.
  56740. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  56741. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  56742. * 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
  56743. * 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
  56744. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  56745. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56746. * 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).
  56747. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56748. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56749. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56750. */
  56751. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  56752. var path = options.path;
  56753. var shape = options.shape;
  56754. var scaleFunction = options.scaleFunction || (function () { return 1; });
  56755. var rotationFunction = options.rotationFunction || (function () { return 0; });
  56756. var ribbonCloseArray = options.ribbonCloseArray || false;
  56757. var ribbonClosePath = options.ribbonClosePath || false;
  56758. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  56759. var updatable = options.updatable;
  56760. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56761. var instance = options.instance;
  56762. var invertUV = options.invertUV || false;
  56763. 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);
  56764. };
  56765. /**
  56766. * Creates lathe mesh.
  56767. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  56768. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  56769. *
  56770. * 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
  56771. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  56772. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  56773. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  56774. * 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.
  56775. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  56776. * 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
  56777. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56778. * 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).
  56779. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56780. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  56781. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56782. */
  56783. MeshBuilder.CreateLathe = function (name, options, scene) {
  56784. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  56785. var closed = (options.closed === undefined) ? true : options.closed;
  56786. var shape = options.shape;
  56787. var radius = options.radius || 1;
  56788. var tessellation = options.tessellation || 64;
  56789. var updatable = options.updatable;
  56790. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56791. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  56792. var pi2 = Math.PI * 2;
  56793. var paths = new Array();
  56794. var invertUV = options.invertUV || false;
  56795. var i = 0;
  56796. var p = 0;
  56797. var step = pi2 / tessellation * arc;
  56798. var rotated;
  56799. var path = new Array();
  56800. ;
  56801. for (i = 0; i <= tessellation; i++) {
  56802. var path = [];
  56803. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  56804. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  56805. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  56806. }
  56807. for (p = 0; p < shape.length; p++) {
  56808. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  56809. path.push(rotated);
  56810. }
  56811. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  56812. 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));
  56813. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  56814. }
  56815. paths.push(path);
  56816. }
  56817. // lathe ribbon
  56818. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  56819. return lathe;
  56820. };
  56821. /**
  56822. * Creates a plane mesh.
  56823. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  56824. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  56825. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  56826. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  56827. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56828. * 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).
  56829. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  56830. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56831. */
  56832. MeshBuilder.CreatePlane = function (name, options, scene) {
  56833. var plane = new BABYLON.Mesh(name, scene);
  56834. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56835. plane._originalBuilderSideOrientation = options.sideOrientation;
  56836. var vertexData = BABYLON.VertexData.CreatePlane(options);
  56837. vertexData.applyToMesh(plane, options.updatable);
  56838. if (options.sourcePlane) {
  56839. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  56840. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  56841. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  56842. plane.rotate(vectorProduct, product);
  56843. }
  56844. return plane;
  56845. };
  56846. /**
  56847. * Creates a ground mesh.
  56848. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  56849. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  56850. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  56851. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56852. */
  56853. MeshBuilder.CreateGround = function (name, options, scene) {
  56854. var ground = new BABYLON.GroundMesh(name, scene);
  56855. ground._setReady(false);
  56856. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  56857. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  56858. ground._width = options.width || 1;
  56859. ground._height = options.height || 1;
  56860. ground._maxX = ground._width / 2;
  56861. ground._maxZ = ground._height / 2;
  56862. ground._minX = -ground._maxX;
  56863. ground._minZ = -ground._maxZ;
  56864. var vertexData = BABYLON.VertexData.CreateGround(options);
  56865. vertexData.applyToMesh(ground, options.updatable);
  56866. ground._setReady(true);
  56867. return ground;
  56868. };
  56869. /**
  56870. * Creates a tiled ground mesh.
  56871. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  56872. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  56873. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  56874. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  56875. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  56876. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  56877. * numbers of subdivisions on the ground width and height of each tile.
  56878. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56879. */
  56880. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  56881. var tiledGround = new BABYLON.Mesh(name, scene);
  56882. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  56883. vertexData.applyToMesh(tiledGround, options.updatable);
  56884. return tiledGround;
  56885. };
  56886. /**
  56887. * Creates a ground mesh from a height map.
  56888. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  56889. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  56890. * The parameter `url` sets the URL of the height map image resource.
  56891. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  56892. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  56893. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  56894. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  56895. * 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.
  56896. * 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).
  56897. * This function is passed the newly built mesh :
  56898. * ```javascript
  56899. * function(mesh) { // do things
  56900. * return; }
  56901. * ```
  56902. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56903. */
  56904. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  56905. var width = options.width || 10.0;
  56906. var height = options.height || 10.0;
  56907. var subdivisions = options.subdivisions || 1 | 0;
  56908. var minHeight = options.minHeight || 0.0;
  56909. var maxHeight = options.maxHeight || 1.0;
  56910. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  56911. var updatable = options.updatable;
  56912. var onReady = options.onReady;
  56913. var ground = new BABYLON.GroundMesh(name, scene);
  56914. ground._subdivisionsX = subdivisions;
  56915. ground._subdivisionsY = subdivisions;
  56916. ground._width = width;
  56917. ground._height = height;
  56918. ground._maxX = ground._width / 2.0;
  56919. ground._maxZ = ground._height / 2.0;
  56920. ground._minX = -ground._maxX;
  56921. ground._minZ = -ground._maxZ;
  56922. ground._setReady(false);
  56923. var onload = function (img) {
  56924. // Getting height map data
  56925. var canvas = document.createElement("canvas");
  56926. var context = canvas.getContext("2d");
  56927. if (!context) {
  56928. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  56929. }
  56930. if (scene.isDisposed) {
  56931. return;
  56932. }
  56933. var bufferWidth = img.width;
  56934. var bufferHeight = img.height;
  56935. canvas.width = bufferWidth;
  56936. canvas.height = bufferHeight;
  56937. context.drawImage(img, 0, 0);
  56938. // Create VertexData from map data
  56939. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  56940. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  56941. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  56942. width: width, height: height,
  56943. subdivisions: subdivisions,
  56944. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  56945. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  56946. });
  56947. vertexData.applyToMesh(ground, updatable);
  56948. //execute ready callback, if set
  56949. if (onReady) {
  56950. onReady(ground);
  56951. }
  56952. ground._setReady(true);
  56953. };
  56954. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  56955. return ground;
  56956. };
  56957. /**
  56958. * Creates a polygon mesh.
  56959. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  56960. * 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.
  56961. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  56962. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  56963. * 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).
  56964. * Remember you can only change the shape positions, not their number when updating a polygon.
  56965. */
  56966. MeshBuilder.CreatePolygon = function (name, options, scene) {
  56967. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  56968. var shape = options.shape;
  56969. var holes = options.holes || [];
  56970. var depth = options.depth || 0;
  56971. var contours = [];
  56972. var hole = [];
  56973. for (var i = 0; i < shape.length; i++) {
  56974. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  56975. }
  56976. var epsilon = 0.00000001;
  56977. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  56978. contours.pop();
  56979. }
  56980. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  56981. for (var hNb = 0; hNb < holes.length; hNb++) {
  56982. hole = [];
  56983. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  56984. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  56985. }
  56986. polygonTriangulation.addHole(hole);
  56987. }
  56988. var polygon = polygonTriangulation.build(options.updatable, depth);
  56989. polygon._originalBuilderSideOrientation = options.sideOrientation;
  56990. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  56991. vertexData.applyToMesh(polygon, options.updatable);
  56992. return polygon;
  56993. };
  56994. ;
  56995. /**
  56996. * Creates an extruded polygon mesh, with depth in the Y direction.
  56997. * 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).
  56998. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  56999. */
  57000. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  57001. return MeshBuilder.CreatePolygon(name, options, scene);
  57002. };
  57003. ;
  57004. /**
  57005. * Creates a tube mesh.
  57006. * 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.
  57007. *
  57008. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  57009. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  57010. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  57011. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  57012. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  57013. * 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.
  57014. * It must return a radius value (positive float) :
  57015. * ```javascript
  57016. * var radiusFunction = function(i, distance) {
  57017. * // do things
  57018. * return radius; }
  57019. * ```
  57020. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  57021. * 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
  57022. * 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
  57023. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57024. * 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).
  57025. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57026. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  57027. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57028. */
  57029. MeshBuilder.CreateTube = function (name, options, scene) {
  57030. var path = options.path;
  57031. var instance = options.instance;
  57032. var radius = 1.0;
  57033. if (instance) {
  57034. radius = instance.radius;
  57035. }
  57036. if (options.radius !== undefined) {
  57037. radius = options.radius;
  57038. }
  57039. ;
  57040. var tessellation = options.tessellation || 64 | 0;
  57041. var radiusFunction = options.radiusFunction || null;
  57042. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  57043. var invertUV = options.invertUV || false;
  57044. var updatable = options.updatable;
  57045. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57046. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  57047. // tube geometry
  57048. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  57049. var tangents = path3D.getTangents();
  57050. var normals = path3D.getNormals();
  57051. var distances = path3D.getDistances();
  57052. var pi2 = Math.PI * 2;
  57053. var step = pi2 / tessellation * arc;
  57054. var returnRadius = function () { return radius; };
  57055. var radiusFunctionFinal = radiusFunction || returnRadius;
  57056. var circlePath;
  57057. var rad;
  57058. var normal;
  57059. var rotated;
  57060. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  57061. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  57062. for (var i = 0; i < path.length; i++) {
  57063. rad = radiusFunctionFinal(i, distances[i]); // current radius
  57064. circlePath = Array(); // current circle array
  57065. normal = normals[i]; // current normal
  57066. for (var t = 0; t < tessellation; t++) {
  57067. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  57068. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  57069. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  57070. rotated.scaleInPlace(rad).addInPlace(path[i]);
  57071. circlePath[t] = rotated;
  57072. }
  57073. circlePaths[index] = circlePath;
  57074. index++;
  57075. }
  57076. // cap
  57077. var capPath = function (nbPoints, pathIndex) {
  57078. var pointCap = Array();
  57079. for (var i = 0; i < nbPoints; i++) {
  57080. pointCap.push(path[pathIndex]);
  57081. }
  57082. return pointCap;
  57083. };
  57084. switch (cap) {
  57085. case BABYLON.Mesh.NO_CAP:
  57086. break;
  57087. case BABYLON.Mesh.CAP_START:
  57088. circlePaths[0] = capPath(tessellation, 0);
  57089. circlePaths[1] = circlePaths[2].slice(0);
  57090. break;
  57091. case BABYLON.Mesh.CAP_END:
  57092. circlePaths[index] = circlePaths[index - 1].slice(0);
  57093. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  57094. break;
  57095. case BABYLON.Mesh.CAP_ALL:
  57096. circlePaths[0] = capPath(tessellation, 0);
  57097. circlePaths[1] = circlePaths[2].slice(0);
  57098. circlePaths[index] = circlePaths[index - 1].slice(0);
  57099. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  57100. break;
  57101. default:
  57102. break;
  57103. }
  57104. return circlePaths;
  57105. };
  57106. var path3D;
  57107. var pathArray;
  57108. if (instance) {
  57109. var arc = options.arc || instance.arc;
  57110. path3D = (instance.path3D).update(path);
  57111. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  57112. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  57113. instance.path3D = path3D;
  57114. instance.pathArray = pathArray;
  57115. instance.arc = arc;
  57116. instance.radius = radius;
  57117. return instance;
  57118. }
  57119. // tube creation
  57120. path3D = new BABYLON.Path3D(path);
  57121. var newPathArray = new Array();
  57122. cap = (cap < 0 || cap > 3) ? 0 : cap;
  57123. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  57124. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  57125. tube.pathArray = pathArray;
  57126. tube.path3D = path3D;
  57127. tube.tessellation = tessellation;
  57128. tube.cap = cap;
  57129. tube.arc = options.arc;
  57130. tube.radius = radius;
  57131. return tube;
  57132. };
  57133. /**
  57134. * Creates a polyhedron mesh.
  57135. *
  57136. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  57137. * 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
  57138. * to choose the wanted type.
  57139. * The parameter `size` (positive float, default 1) sets the polygon size.
  57140. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  57141. * 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`.
  57142. * 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
  57143. * 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)`).
  57144. * 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
  57145. * 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.
  57146. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  57147. * 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).
  57148. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  57149. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  57150. */
  57151. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  57152. var polyhedron = new BABYLON.Mesh(name, scene);
  57153. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  57154. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  57155. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  57156. vertexData.applyToMesh(polyhedron, options.updatable);
  57157. return polyhedron;
  57158. };
  57159. /**
  57160. * Creates a decal mesh.
  57161. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  57162. * 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.
  57163. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  57164. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  57165. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  57166. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  57167. */
  57168. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  57169. var indices = sourceMesh.getIndices();
  57170. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  57171. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  57172. var position = options.position || BABYLON.Vector3.Zero();
  57173. var normal = options.normal || BABYLON.Vector3.Up();
  57174. var size = options.size || BABYLON.Vector3.One();
  57175. var angle = options.angle || 0;
  57176. // Getting correct rotation
  57177. if (!normal) {
  57178. var target = new BABYLON.Vector3(0, 0, 1);
  57179. var camera = sourceMesh.getScene().activeCamera;
  57180. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  57181. normal = camera.globalPosition.subtract(cameraWorldTarget);
  57182. }
  57183. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  57184. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  57185. var pitch = Math.atan2(normal.y, len);
  57186. // Matrix
  57187. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  57188. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  57189. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  57190. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  57191. var vertexData = new BABYLON.VertexData();
  57192. vertexData.indices = [];
  57193. vertexData.positions = [];
  57194. vertexData.normals = [];
  57195. vertexData.uvs = [];
  57196. var currentVertexDataIndex = 0;
  57197. var extractDecalVector3 = function (indexId) {
  57198. var result = new BABYLON.PositionNormalVertex();
  57199. if (!indices || !positions || !normals) {
  57200. return result;
  57201. }
  57202. var vertexId = indices[indexId];
  57203. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  57204. // Send vector to decal local world
  57205. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  57206. // Get normal
  57207. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  57208. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  57209. return result;
  57210. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  57211. var clip = function (vertices, axis) {
  57212. if (vertices.length === 0) {
  57213. return vertices;
  57214. }
  57215. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  57216. var clipVertices = function (v0, v1) {
  57217. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  57218. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  57219. };
  57220. var result = new Array();
  57221. for (var index = 0; index < vertices.length; index += 3) {
  57222. var v1Out;
  57223. var v2Out;
  57224. var v3Out;
  57225. var total = 0;
  57226. var nV1 = null;
  57227. var nV2 = null;
  57228. var nV3 = null;
  57229. var nV4 = null;
  57230. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  57231. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  57232. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  57233. v1Out = d1 > 0;
  57234. v2Out = d2 > 0;
  57235. v3Out = d3 > 0;
  57236. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  57237. switch (total) {
  57238. case 0:
  57239. result.push(vertices[index]);
  57240. result.push(vertices[index + 1]);
  57241. result.push(vertices[index + 2]);
  57242. break;
  57243. case 1:
  57244. if (v1Out) {
  57245. nV1 = vertices[index + 1];
  57246. nV2 = vertices[index + 2];
  57247. nV3 = clipVertices(vertices[index], nV1);
  57248. nV4 = clipVertices(vertices[index], nV2);
  57249. }
  57250. if (v2Out) {
  57251. nV1 = vertices[index];
  57252. nV2 = vertices[index + 2];
  57253. nV3 = clipVertices(vertices[index + 1], nV1);
  57254. nV4 = clipVertices(vertices[index + 1], nV2);
  57255. result.push(nV3);
  57256. result.push(nV2.clone());
  57257. result.push(nV1.clone());
  57258. result.push(nV2.clone());
  57259. result.push(nV3.clone());
  57260. result.push(nV4);
  57261. break;
  57262. }
  57263. if (v3Out) {
  57264. nV1 = vertices[index];
  57265. nV2 = vertices[index + 1];
  57266. nV3 = clipVertices(vertices[index + 2], nV1);
  57267. nV4 = clipVertices(vertices[index + 2], nV2);
  57268. }
  57269. if (nV1 && nV2 && nV3 && nV4) {
  57270. result.push(nV1.clone());
  57271. result.push(nV2.clone());
  57272. result.push(nV3);
  57273. result.push(nV4);
  57274. result.push(nV3.clone());
  57275. result.push(nV2.clone());
  57276. }
  57277. break;
  57278. case 2:
  57279. if (!v1Out) {
  57280. nV1 = vertices[index].clone();
  57281. nV2 = clipVertices(nV1, vertices[index + 1]);
  57282. nV3 = clipVertices(nV1, vertices[index + 2]);
  57283. result.push(nV1);
  57284. result.push(nV2);
  57285. result.push(nV3);
  57286. }
  57287. if (!v2Out) {
  57288. nV1 = vertices[index + 1].clone();
  57289. nV2 = clipVertices(nV1, vertices[index + 2]);
  57290. nV3 = clipVertices(nV1, vertices[index]);
  57291. result.push(nV1);
  57292. result.push(nV2);
  57293. result.push(nV3);
  57294. }
  57295. if (!v3Out) {
  57296. nV1 = vertices[index + 2].clone();
  57297. nV2 = clipVertices(nV1, vertices[index]);
  57298. nV3 = clipVertices(nV1, vertices[index + 1]);
  57299. result.push(nV1);
  57300. result.push(nV2);
  57301. result.push(nV3);
  57302. }
  57303. break;
  57304. case 3:
  57305. break;
  57306. }
  57307. }
  57308. return result;
  57309. };
  57310. for (var index = 0; index < indices.length; index += 3) {
  57311. var faceVertices = new Array();
  57312. faceVertices.push(extractDecalVector3(index));
  57313. faceVertices.push(extractDecalVector3(index + 1));
  57314. faceVertices.push(extractDecalVector3(index + 2));
  57315. // Clip
  57316. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  57317. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  57318. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  57319. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  57320. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  57321. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  57322. if (faceVertices.length === 0) {
  57323. continue;
  57324. }
  57325. // Add UVs and get back to world
  57326. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  57327. var vertex = faceVertices[vIndex];
  57328. //TODO check for Int32Array | Uint32Array | Uint16Array
  57329. vertexData.indices.push(currentVertexDataIndex);
  57330. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  57331. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  57332. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  57333. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  57334. currentVertexDataIndex++;
  57335. }
  57336. }
  57337. // Return mesh
  57338. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  57339. vertexData.applyToMesh(decal);
  57340. decal.position = position.clone();
  57341. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  57342. return decal;
  57343. };
  57344. // Privates
  57345. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  57346. // extrusion geometry
  57347. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  57348. var tangents = path3D.getTangents();
  57349. var normals = path3D.getNormals();
  57350. var binormals = path3D.getBinormals();
  57351. var distances = path3D.getDistances();
  57352. var angle = 0;
  57353. var returnScale = function () { return scale !== null ? scale : 1; };
  57354. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  57355. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  57356. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  57357. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  57358. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  57359. for (var i = 0; i < curve.length; i++) {
  57360. var shapePath = new Array();
  57361. var angleStep = rotate(i, distances[i]);
  57362. var scaleRatio = scl(i, distances[i]);
  57363. for (var p = 0; p < shape.length; p++) {
  57364. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  57365. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  57366. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  57367. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  57368. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  57369. shapePath[p] = rotated;
  57370. }
  57371. shapePaths[index] = shapePath;
  57372. angle += angleStep;
  57373. index++;
  57374. }
  57375. // cap
  57376. var capPath = function (shapePath) {
  57377. var pointCap = Array();
  57378. var barycenter = BABYLON.Vector3.Zero();
  57379. var i;
  57380. for (i = 0; i < shapePath.length; i++) {
  57381. barycenter.addInPlace(shapePath[i]);
  57382. }
  57383. barycenter.scaleInPlace(1.0 / shapePath.length);
  57384. for (i = 0; i < shapePath.length; i++) {
  57385. pointCap.push(barycenter);
  57386. }
  57387. return pointCap;
  57388. };
  57389. switch (cap) {
  57390. case BABYLON.Mesh.NO_CAP:
  57391. break;
  57392. case BABYLON.Mesh.CAP_START:
  57393. shapePaths[0] = capPath(shapePaths[2]);
  57394. shapePaths[1] = shapePaths[2];
  57395. break;
  57396. case BABYLON.Mesh.CAP_END:
  57397. shapePaths[index] = shapePaths[index - 1];
  57398. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  57399. break;
  57400. case BABYLON.Mesh.CAP_ALL:
  57401. shapePaths[0] = capPath(shapePaths[2]);
  57402. shapePaths[1] = shapePaths[2];
  57403. shapePaths[index] = shapePaths[index - 1];
  57404. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  57405. break;
  57406. default:
  57407. break;
  57408. }
  57409. return shapePaths;
  57410. };
  57411. var path3D;
  57412. var pathArray;
  57413. if (instance) {
  57414. path3D = (instance.path3D).update(curve);
  57415. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  57416. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  57417. return instance;
  57418. }
  57419. // extruded shape creation
  57420. path3D = new BABYLON.Path3D(curve);
  57421. var newShapePaths = new Array();
  57422. cap = (cap < 0 || cap > 3) ? 0 : cap;
  57423. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  57424. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  57425. extrudedGeneric.pathArray = pathArray;
  57426. extrudedGeneric.path3D = path3D;
  57427. extrudedGeneric.cap = cap;
  57428. return extrudedGeneric;
  57429. };
  57430. return MeshBuilder;
  57431. }());
  57432. BABYLON.MeshBuilder = MeshBuilder;
  57433. })(BABYLON || (BABYLON = {}));
  57434. //# sourceMappingURL=babylon.meshBuilder.js.map
  57435. "use strict";
  57436. var BABYLON;
  57437. (function (BABYLON) {
  57438. /**
  57439. * Draco compression (https://google.github.io/draco/)
  57440. */
  57441. var DracoCompression = /** @class */ (function () {
  57442. /**
  57443. * Constructor
  57444. * @param numWorkers The number of workers for async operations
  57445. */
  57446. function DracoCompression(numWorkers) {
  57447. if (numWorkers === void 0) { numWorkers = (navigator.hardwareConcurrency || 4); }
  57448. var workerBlobUrl = URL && URL.createObjectURL && URL.createObjectURL(new Blob(["(" + DracoCompression._Worker.toString() + ")()"], { type: "application/javascript" }));
  57449. if (!workerBlobUrl || !Worker) {
  57450. BABYLON.Tools.Error("Draco Compression disabled. The current context doesn't support worker creation or URL.createObjectURL");
  57451. return;
  57452. }
  57453. var workers = new Array(numWorkers);
  57454. for (var i = 0; i < workers.length; i++) {
  57455. var worker = new Worker(workerBlobUrl);
  57456. worker.postMessage({ id: "initDecoder", url: DracoCompression.DecoderUrl });
  57457. workers[i] = worker;
  57458. }
  57459. this._workerPool = new BABYLON.WorkerPool(workers);
  57460. }
  57461. /**
  57462. * Stop all async operations and release resources.
  57463. */
  57464. DracoCompression.prototype.dispose = function () {
  57465. this._workerPool.dispose();
  57466. delete this._workerPool;
  57467. };
  57468. /**
  57469. * Decode Draco compressed mesh data to vertex data.
  57470. * @param data The array buffer view for the Draco compression data
  57471. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  57472. * @returns A promise that resolves with the decoded vertex data
  57473. */
  57474. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  57475. var _this = this;
  57476. return new Promise(function (resolve, reject) {
  57477. _this._workerPool.push(function (worker, onComplete) {
  57478. var vertexData = new BABYLON.VertexData();
  57479. var onError = function (error) {
  57480. worker.removeEventListener("error", onError);
  57481. worker.removeEventListener("message", onMessage);
  57482. reject(error);
  57483. onComplete();
  57484. };
  57485. var onMessage = function (message) {
  57486. if (message.data === "done") {
  57487. worker.removeEventListener("error", onError);
  57488. worker.removeEventListener("message", onMessage);
  57489. resolve(vertexData);
  57490. onComplete();
  57491. }
  57492. else if (message.data.id === "indices") {
  57493. vertexData.indices = message.data.value;
  57494. }
  57495. else {
  57496. vertexData.set(message.data.value, message.data.id);
  57497. }
  57498. };
  57499. worker.addEventListener("error", onError);
  57500. worker.addEventListener("message", onMessage);
  57501. var dataCopy = new Uint8Array(data.byteLength);
  57502. dataCopy.set(new Uint8Array(data.buffer, data.byteOffset, data.byteLength));
  57503. worker.postMessage({ id: "decodeMesh", data: dataCopy, attributes: attributes }, [dataCopy.buffer]);
  57504. });
  57505. });
  57506. };
  57507. /**
  57508. * The worker function that gets converted to a blob url to pass into a worker.
  57509. */
  57510. DracoCompression._Worker = function () {
  57511. // self is actually a DedicatedWorkerGlobalScope
  57512. var _self = self;
  57513. var decodeMesh = function (data, attributes) {
  57514. var dracoModule = new DracoDecoderModule();
  57515. var buffer = new dracoModule.DecoderBuffer();
  57516. buffer.Init(data, data.byteLength);
  57517. var decoder = new dracoModule.Decoder();
  57518. var geometry;
  57519. var status;
  57520. try {
  57521. var type = decoder.GetEncodedGeometryType(buffer);
  57522. switch (type) {
  57523. case dracoModule.TRIANGULAR_MESH:
  57524. geometry = new dracoModule.Mesh();
  57525. status = decoder.DecodeBufferToMesh(buffer, geometry);
  57526. break;
  57527. case dracoModule.POINT_CLOUD:
  57528. geometry = new dracoModule.PointCloud();
  57529. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  57530. break;
  57531. default:
  57532. throw new Error("Invalid geometry type " + type);
  57533. }
  57534. if (!status.ok() || !geometry.ptr) {
  57535. throw new Error(status.error_msg());
  57536. }
  57537. var numPoints = geometry.num_points();
  57538. if (type === dracoModule.TRIANGULAR_MESH) {
  57539. var numFaces = geometry.num_faces();
  57540. var faceIndices = new dracoModule.DracoInt32Array();
  57541. try {
  57542. var indices = new Uint32Array(numFaces * 3);
  57543. for (var i = 0; i < numFaces; i++) {
  57544. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  57545. var offset = i * 3;
  57546. indices[offset + 0] = faceIndices.GetValue(0);
  57547. indices[offset + 1] = faceIndices.GetValue(1);
  57548. indices[offset + 2] = faceIndices.GetValue(2);
  57549. }
  57550. _self.postMessage({ id: "indices", value: indices }, [indices.buffer]);
  57551. }
  57552. finally {
  57553. dracoModule.destroy(faceIndices);
  57554. }
  57555. }
  57556. for (var kind in attributes) {
  57557. var uniqueId = attributes[kind];
  57558. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  57559. var dracoData = new dracoModule.DracoFloat32Array();
  57560. try {
  57561. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  57562. var babylonData = new Float32Array(numPoints * attribute.num_components());
  57563. for (var i = 0; i < babylonData.length; i++) {
  57564. babylonData[i] = dracoData.GetValue(i);
  57565. }
  57566. _self.postMessage({ id: kind, value: babylonData }, [babylonData.buffer]);
  57567. }
  57568. finally {
  57569. dracoModule.destroy(dracoData);
  57570. }
  57571. }
  57572. }
  57573. finally {
  57574. if (geometry) {
  57575. dracoModule.destroy(geometry);
  57576. }
  57577. dracoModule.destroy(decoder);
  57578. dracoModule.destroy(buffer);
  57579. }
  57580. _self.postMessage("done");
  57581. };
  57582. _self.onmessage = function (event) {
  57583. switch (event.data.id) {
  57584. case "initDecoder": {
  57585. importScripts(event.data.url);
  57586. break;
  57587. }
  57588. case "decodeMesh": {
  57589. decodeMesh(event.data.data, event.data.attributes);
  57590. break;
  57591. }
  57592. }
  57593. };
  57594. };
  57595. DracoCompression._GetDefaultDecoderUrl = function () {
  57596. if (!BABYLON.Tools.IsWindowObjectExist) {
  57597. return null;
  57598. }
  57599. for (var i = 0; i < document.scripts.length; i++) {
  57600. if (document.scripts[i].type === "text/x-draco-decoder") {
  57601. return document.scripts[i].src;
  57602. }
  57603. }
  57604. return null;
  57605. };
  57606. /**
  57607. * Gets the url to the draco decoder if available.
  57608. */
  57609. DracoCompression.DecoderUrl = DracoCompression._GetDefaultDecoderUrl();
  57610. return DracoCompression;
  57611. }());
  57612. BABYLON.DracoCompression = DracoCompression;
  57613. })(BABYLON || (BABYLON = {}));
  57614. //# sourceMappingURL=babylon.dracoCompression.js.map
  57615. "use strict";
  57616. var BABYLON;
  57617. (function (BABYLON) {
  57618. var AudioEngine = /** @class */ (function () {
  57619. function AudioEngine() {
  57620. this._audioContext = null;
  57621. this._audioContextInitialized = false;
  57622. this.canUseWebAudio = false;
  57623. this.WarnedWebAudioUnsupported = false;
  57624. this.unlocked = false;
  57625. this.isMP3supported = false;
  57626. this.isOGGsupported = false;
  57627. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  57628. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  57629. this.canUseWebAudio = true;
  57630. }
  57631. var audioElem = document.createElement('audio');
  57632. try {
  57633. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  57634. this.isMP3supported = true;
  57635. }
  57636. }
  57637. catch (e) {
  57638. // protect error during capability check.
  57639. }
  57640. try {
  57641. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  57642. this.isOGGsupported = true;
  57643. }
  57644. }
  57645. catch (e) {
  57646. // protect error during capability check.
  57647. }
  57648. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  57649. this._unlockiOSaudio();
  57650. }
  57651. else {
  57652. this.unlocked = true;
  57653. }
  57654. }
  57655. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  57656. get: function () {
  57657. if (!this._audioContextInitialized) {
  57658. this._initializeAudioContext();
  57659. }
  57660. return this._audioContext;
  57661. },
  57662. enumerable: true,
  57663. configurable: true
  57664. });
  57665. AudioEngine.prototype._unlockiOSaudio = function () {
  57666. var _this = this;
  57667. var unlockaudio = function () {
  57668. if (!_this.audioContext) {
  57669. return;
  57670. }
  57671. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  57672. var source = _this.audioContext.createBufferSource();
  57673. source.buffer = buffer;
  57674. source.connect(_this.audioContext.destination);
  57675. source.start(0);
  57676. setTimeout(function () {
  57677. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  57678. _this.unlocked = true;
  57679. window.removeEventListener('touchend', unlockaudio, false);
  57680. if (_this.onAudioUnlocked) {
  57681. _this.onAudioUnlocked();
  57682. }
  57683. }
  57684. }, 0);
  57685. };
  57686. window.addEventListener('touchend', unlockaudio, false);
  57687. };
  57688. AudioEngine.prototype._initializeAudioContext = function () {
  57689. try {
  57690. if (this.canUseWebAudio) {
  57691. this._audioContext = new AudioContext();
  57692. // create a global volume gain node
  57693. this.masterGain = this._audioContext.createGain();
  57694. this.masterGain.gain.value = 1;
  57695. this.masterGain.connect(this._audioContext.destination);
  57696. this._audioContextInitialized = true;
  57697. }
  57698. }
  57699. catch (e) {
  57700. this.canUseWebAudio = false;
  57701. BABYLON.Tools.Error("Web Audio: " + e.message);
  57702. }
  57703. };
  57704. AudioEngine.prototype.dispose = function () {
  57705. if (this.canUseWebAudio && this._audioContextInitialized) {
  57706. if (this._connectedAnalyser && this._audioContext) {
  57707. this._connectedAnalyser.stopDebugCanvas();
  57708. this._connectedAnalyser.dispose();
  57709. this.masterGain.disconnect();
  57710. this.masterGain.connect(this._audioContext.destination);
  57711. this._connectedAnalyser = null;
  57712. }
  57713. this.masterGain.gain.value = 1;
  57714. }
  57715. this.WarnedWebAudioUnsupported = false;
  57716. };
  57717. AudioEngine.prototype.getGlobalVolume = function () {
  57718. if (this.canUseWebAudio && this._audioContextInitialized) {
  57719. return this.masterGain.gain.value;
  57720. }
  57721. else {
  57722. return -1;
  57723. }
  57724. };
  57725. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  57726. if (this.canUseWebAudio && this._audioContextInitialized) {
  57727. this.masterGain.gain.value = newVolume;
  57728. }
  57729. };
  57730. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  57731. if (this._connectedAnalyser) {
  57732. this._connectedAnalyser.stopDebugCanvas();
  57733. }
  57734. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  57735. this._connectedAnalyser = analyser;
  57736. this.masterGain.disconnect();
  57737. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  57738. }
  57739. };
  57740. return AudioEngine;
  57741. }());
  57742. BABYLON.AudioEngine = AudioEngine;
  57743. })(BABYLON || (BABYLON = {}));
  57744. //# sourceMappingURL=babylon.audioEngine.js.map
  57745. "use strict";
  57746. var BABYLON;
  57747. (function (BABYLON) {
  57748. var Sound = /** @class */ (function () {
  57749. /**
  57750. * Create a sound and attach it to a scene
  57751. * @param name Name of your sound
  57752. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  57753. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  57754. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  57755. */
  57756. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  57757. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  57758. var _this = this;
  57759. this.autoplay = false;
  57760. this.loop = false;
  57761. this.useCustomAttenuation = false;
  57762. this.spatialSound = false;
  57763. this.refDistance = 1;
  57764. this.rolloffFactor = 1;
  57765. this.maxDistance = 100;
  57766. this.distanceModel = "linear";
  57767. this._panningModel = "equalpower";
  57768. this._playbackRate = 1;
  57769. this._streaming = false;
  57770. this._startTime = 0;
  57771. this._startOffset = 0;
  57772. this._position = BABYLON.Vector3.Zero();
  57773. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  57774. this._volume = 1;
  57775. this._isReadyToPlay = false;
  57776. this.isPlaying = false;
  57777. this.isPaused = false;
  57778. this._isDirectional = false;
  57779. // Used if you'd like to create a directional sound.
  57780. // If not set, the sound will be omnidirectional
  57781. this._coneInnerAngle = 360;
  57782. this._coneOuterAngle = 360;
  57783. this._coneOuterGain = 0;
  57784. this._isOutputConnected = false;
  57785. this._urlType = "Unknown";
  57786. this.name = name;
  57787. this._scene = scene;
  57788. this._readyToPlayCallback = readyToPlayCallback;
  57789. // Default custom attenuation function is a linear attenuation
  57790. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  57791. if (currentDistance < maxDistance) {
  57792. return currentVolume * (1 - currentDistance / maxDistance);
  57793. }
  57794. else {
  57795. return 0;
  57796. }
  57797. };
  57798. if (options) {
  57799. this.autoplay = options.autoplay || false;
  57800. this.loop = options.loop || false;
  57801. // if volume === 0, we need another way to check this option
  57802. if (options.volume !== undefined) {
  57803. this._volume = options.volume;
  57804. }
  57805. this.spatialSound = options.spatialSound || false;
  57806. this.maxDistance = options.maxDistance || 100;
  57807. this.useCustomAttenuation = options.useCustomAttenuation || false;
  57808. this.rolloffFactor = options.rolloffFactor || 1;
  57809. this.refDistance = options.refDistance || 1;
  57810. this.distanceModel = options.distanceModel || "linear";
  57811. this._playbackRate = options.playbackRate || 1;
  57812. this._streaming = options.streaming || false;
  57813. }
  57814. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  57815. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  57816. this._soundGain.gain.value = this._volume;
  57817. this._inputAudioNode = this._soundGain;
  57818. this._ouputAudioNode = this._soundGain;
  57819. if (this.spatialSound) {
  57820. this._createSpatialParameters();
  57821. }
  57822. this._scene.mainSoundTrack.AddSound(this);
  57823. var validParameter = true;
  57824. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  57825. if (urlOrArrayBuffer) {
  57826. if (typeof (urlOrArrayBuffer) === "string")
  57827. this._urlType = "String";
  57828. if (Array.isArray(urlOrArrayBuffer))
  57829. this._urlType = "Array";
  57830. if (urlOrArrayBuffer instanceof ArrayBuffer)
  57831. this._urlType = "ArrayBuffer";
  57832. var urls = [];
  57833. var codecSupportedFound = false;
  57834. switch (this._urlType) {
  57835. case "ArrayBuffer":
  57836. if (urlOrArrayBuffer.byteLength > 0) {
  57837. codecSupportedFound = true;
  57838. this._soundLoaded(urlOrArrayBuffer);
  57839. }
  57840. break;
  57841. case "String":
  57842. urls.push(urlOrArrayBuffer);
  57843. case "Array":
  57844. if (urls.length === 0)
  57845. urls = urlOrArrayBuffer;
  57846. // If we found a supported format, we load it immediately and stop the loop
  57847. for (var i = 0; i < urls.length; i++) {
  57848. var url = urls[i];
  57849. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  57850. codecSupportedFound = true;
  57851. }
  57852. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  57853. codecSupportedFound = true;
  57854. }
  57855. if (url.indexOf(".wav", url.length - 4) !== -1) {
  57856. codecSupportedFound = true;
  57857. }
  57858. if (url.indexOf("blob:") !== -1) {
  57859. codecSupportedFound = true;
  57860. }
  57861. if (codecSupportedFound) {
  57862. // Loading sound using XHR2
  57863. if (!this._streaming) {
  57864. this._scene._loadFile(url, function (data) { _this._soundLoaded(data); }, undefined, true, true);
  57865. }
  57866. else {
  57867. this._htmlAudioElement = new Audio(url);
  57868. this._htmlAudioElement.controls = false;
  57869. this._htmlAudioElement.loop = this.loop;
  57870. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  57871. this._htmlAudioElement.preload = "auto";
  57872. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  57873. _this._isReadyToPlay = true;
  57874. if (_this.autoplay) {
  57875. _this.play();
  57876. }
  57877. if (_this._readyToPlayCallback) {
  57878. _this._readyToPlayCallback();
  57879. }
  57880. });
  57881. document.body.appendChild(this._htmlAudioElement);
  57882. }
  57883. break;
  57884. }
  57885. }
  57886. break;
  57887. default:
  57888. validParameter = false;
  57889. break;
  57890. }
  57891. if (!validParameter) {
  57892. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  57893. }
  57894. else {
  57895. if (!codecSupportedFound) {
  57896. this._isReadyToPlay = true;
  57897. // Simulating a ready to play event to avoid breaking code path
  57898. if (this._readyToPlayCallback) {
  57899. window.setTimeout(function () {
  57900. if (_this._readyToPlayCallback) {
  57901. _this._readyToPlayCallback();
  57902. }
  57903. }, 1000);
  57904. }
  57905. }
  57906. }
  57907. }
  57908. }
  57909. else {
  57910. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  57911. this._scene.mainSoundTrack.AddSound(this);
  57912. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  57913. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  57914. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  57915. }
  57916. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  57917. if (this._readyToPlayCallback) {
  57918. window.setTimeout(function () {
  57919. if (_this._readyToPlayCallback) {
  57920. _this._readyToPlayCallback();
  57921. }
  57922. }, 1000);
  57923. }
  57924. }
  57925. }
  57926. Sound.prototype.dispose = function () {
  57927. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  57928. if (this.isPlaying) {
  57929. this.stop();
  57930. }
  57931. this._isReadyToPlay = false;
  57932. if (this.soundTrackId === -1) {
  57933. this._scene.mainSoundTrack.RemoveSound(this);
  57934. }
  57935. else {
  57936. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  57937. }
  57938. if (this._soundGain) {
  57939. this._soundGain.disconnect();
  57940. this._soundGain = null;
  57941. }
  57942. if (this._soundPanner) {
  57943. this._soundPanner.disconnect();
  57944. this._soundPanner = null;
  57945. }
  57946. if (this._soundSource) {
  57947. this._soundSource.disconnect();
  57948. this._soundSource = null;
  57949. }
  57950. this._audioBuffer = null;
  57951. if (this._htmlAudioElement) {
  57952. this._htmlAudioElement.pause();
  57953. this._htmlAudioElement.src = "";
  57954. document.body.removeChild(this._htmlAudioElement);
  57955. }
  57956. if (this._connectedMesh && this._registerFunc) {
  57957. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  57958. this._connectedMesh = null;
  57959. }
  57960. }
  57961. };
  57962. Sound.prototype.isReady = function () {
  57963. return this._isReadyToPlay;
  57964. };
  57965. Sound.prototype._soundLoaded = function (audioData) {
  57966. var _this = this;
  57967. if (!BABYLON.Engine.audioEngine.audioContext) {
  57968. return;
  57969. }
  57970. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  57971. _this._audioBuffer = buffer;
  57972. _this._isReadyToPlay = true;
  57973. if (_this.autoplay) {
  57974. _this.play();
  57975. }
  57976. if (_this._readyToPlayCallback) {
  57977. _this._readyToPlayCallback();
  57978. }
  57979. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  57980. };
  57981. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  57982. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  57983. this._audioBuffer = audioBuffer;
  57984. this._isReadyToPlay = true;
  57985. }
  57986. };
  57987. Sound.prototype.updateOptions = function (options) {
  57988. if (options) {
  57989. this.loop = options.loop || this.loop;
  57990. this.maxDistance = options.maxDistance || this.maxDistance;
  57991. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  57992. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  57993. this.refDistance = options.refDistance || this.refDistance;
  57994. this.distanceModel = options.distanceModel || this.distanceModel;
  57995. this._playbackRate = options.playbackRate || this._playbackRate;
  57996. this._updateSpatialParameters();
  57997. if (this.isPlaying) {
  57998. if (this._streaming) {
  57999. this._htmlAudioElement.playbackRate = this._playbackRate;
  58000. }
  58001. else {
  58002. if (this._soundSource) {
  58003. this._soundSource.playbackRate.value = this._playbackRate;
  58004. }
  58005. }
  58006. }
  58007. }
  58008. };
  58009. Sound.prototype._createSpatialParameters = function () {
  58010. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  58011. if (this._scene.headphone) {
  58012. this._panningModel = "HRTF";
  58013. }
  58014. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  58015. this._updateSpatialParameters();
  58016. this._soundPanner.connect(this._ouputAudioNode);
  58017. this._inputAudioNode = this._soundPanner;
  58018. }
  58019. };
  58020. Sound.prototype._updateSpatialParameters = function () {
  58021. if (this.spatialSound && this._soundPanner) {
  58022. if (this.useCustomAttenuation) {
  58023. // Tricks to disable in a way embedded Web Audio attenuation
  58024. this._soundPanner.distanceModel = "linear";
  58025. this._soundPanner.maxDistance = Number.MAX_VALUE;
  58026. this._soundPanner.refDistance = 1;
  58027. this._soundPanner.rolloffFactor = 1;
  58028. this._soundPanner.panningModel = this._panningModel;
  58029. }
  58030. else {
  58031. this._soundPanner.distanceModel = this.distanceModel;
  58032. this._soundPanner.maxDistance = this.maxDistance;
  58033. this._soundPanner.refDistance = this.refDistance;
  58034. this._soundPanner.rolloffFactor = this.rolloffFactor;
  58035. this._soundPanner.panningModel = this._panningModel;
  58036. }
  58037. }
  58038. };
  58039. Sound.prototype.switchPanningModelToHRTF = function () {
  58040. this._panningModel = "HRTF";
  58041. this._switchPanningModel();
  58042. };
  58043. Sound.prototype.switchPanningModelToEqualPower = function () {
  58044. this._panningModel = "equalpower";
  58045. this._switchPanningModel();
  58046. };
  58047. Sound.prototype._switchPanningModel = function () {
  58048. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  58049. this._soundPanner.panningModel = this._panningModel;
  58050. }
  58051. };
  58052. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  58053. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58054. if (this._isOutputConnected) {
  58055. this._ouputAudioNode.disconnect();
  58056. }
  58057. this._ouputAudioNode.connect(soundTrackAudioNode);
  58058. this._isOutputConnected = true;
  58059. }
  58060. };
  58061. /**
  58062. * Transform this sound into a directional source
  58063. * @param coneInnerAngle Size of the inner cone in degree
  58064. * @param coneOuterAngle Size of the outer cone in degree
  58065. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  58066. */
  58067. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  58068. if (coneOuterAngle < coneInnerAngle) {
  58069. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  58070. return;
  58071. }
  58072. this._coneInnerAngle = coneInnerAngle;
  58073. this._coneOuterAngle = coneOuterAngle;
  58074. this._coneOuterGain = coneOuterGain;
  58075. this._isDirectional = true;
  58076. if (this.isPlaying && this.loop) {
  58077. this.stop();
  58078. this.play();
  58079. }
  58080. };
  58081. Sound.prototype.setPosition = function (newPosition) {
  58082. this._position = newPosition;
  58083. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  58084. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  58085. }
  58086. };
  58087. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  58088. this._localDirection = newLocalDirection;
  58089. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  58090. this._updateDirection();
  58091. }
  58092. };
  58093. Sound.prototype._updateDirection = function () {
  58094. if (!this._connectedMesh || !this._soundPanner) {
  58095. return;
  58096. }
  58097. var mat = this._connectedMesh.getWorldMatrix();
  58098. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  58099. direction.normalize();
  58100. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  58101. };
  58102. Sound.prototype.updateDistanceFromListener = function () {
  58103. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  58104. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  58105. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  58106. }
  58107. };
  58108. Sound.prototype.setAttenuationFunction = function (callback) {
  58109. this._customAttenuationFunction = callback;
  58110. };
  58111. /**
  58112. * Play the sound
  58113. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  58114. * @param offset (optional) Start the sound setting it at a specific time
  58115. */
  58116. Sound.prototype.play = function (time, offset) {
  58117. var _this = this;
  58118. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  58119. try {
  58120. if (this._startOffset < 0) {
  58121. time = -this._startOffset;
  58122. this._startOffset = 0;
  58123. }
  58124. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  58125. if (!this._soundSource || !this._streamingSource) {
  58126. if (this.spatialSound && this._soundPanner) {
  58127. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  58128. if (this._isDirectional) {
  58129. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  58130. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  58131. this._soundPanner.coneOuterGain = this._coneOuterGain;
  58132. if (this._connectedMesh) {
  58133. this._updateDirection();
  58134. }
  58135. else {
  58136. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  58137. }
  58138. }
  58139. }
  58140. }
  58141. if (this._streaming) {
  58142. if (!this._streamingSource) {
  58143. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  58144. this._htmlAudioElement.onended = function () { _this._onended(); };
  58145. this._htmlAudioElement.playbackRate = this._playbackRate;
  58146. }
  58147. this._streamingSource.disconnect();
  58148. this._streamingSource.connect(this._inputAudioNode);
  58149. this._htmlAudioElement.play();
  58150. }
  58151. else {
  58152. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  58153. this._soundSource.buffer = this._audioBuffer;
  58154. this._soundSource.connect(this._inputAudioNode);
  58155. this._soundSource.loop = this.loop;
  58156. this._soundSource.playbackRate.value = this._playbackRate;
  58157. this._soundSource.onended = function () { _this._onended(); };
  58158. if (this._soundSource.buffer) {
  58159. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  58160. }
  58161. }
  58162. this._startTime = startTime;
  58163. this.isPlaying = true;
  58164. this.isPaused = false;
  58165. }
  58166. catch (ex) {
  58167. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  58168. }
  58169. }
  58170. };
  58171. Sound.prototype._onended = function () {
  58172. this.isPlaying = false;
  58173. if (this.onended) {
  58174. this.onended();
  58175. }
  58176. };
  58177. /**
  58178. * Stop the sound
  58179. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  58180. */
  58181. Sound.prototype.stop = function (time) {
  58182. if (this.isPlaying) {
  58183. if (this._streaming) {
  58184. this._htmlAudioElement.pause();
  58185. // Test needed for Firefox or it will generate an Invalid State Error
  58186. if (this._htmlAudioElement.currentTime > 0) {
  58187. this._htmlAudioElement.currentTime = 0;
  58188. }
  58189. }
  58190. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  58191. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  58192. this._soundSource.stop(stopTime);
  58193. this._soundSource.onended = function () { };
  58194. if (!this.isPaused) {
  58195. this._startOffset = 0;
  58196. }
  58197. }
  58198. this.isPlaying = false;
  58199. }
  58200. };
  58201. Sound.prototype.pause = function () {
  58202. if (this.isPlaying) {
  58203. this.isPaused = true;
  58204. if (this._streaming) {
  58205. this._htmlAudioElement.pause();
  58206. }
  58207. else if (BABYLON.Engine.audioEngine.audioContext) {
  58208. this.stop(0);
  58209. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  58210. }
  58211. }
  58212. };
  58213. Sound.prototype.setVolume = function (newVolume, time) {
  58214. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  58215. if (time && BABYLON.Engine.audioEngine.audioContext) {
  58216. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  58217. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  58218. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  58219. }
  58220. else {
  58221. this._soundGain.gain.value = newVolume;
  58222. }
  58223. }
  58224. this._volume = newVolume;
  58225. };
  58226. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  58227. this._playbackRate = newPlaybackRate;
  58228. if (this.isPlaying) {
  58229. if (this._streaming) {
  58230. this._htmlAudioElement.playbackRate = this._playbackRate;
  58231. }
  58232. else if (this._soundSource) {
  58233. this._soundSource.playbackRate.value = this._playbackRate;
  58234. }
  58235. }
  58236. };
  58237. Sound.prototype.getVolume = function () {
  58238. return this._volume;
  58239. };
  58240. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  58241. var _this = this;
  58242. if (this._connectedMesh && this._registerFunc) {
  58243. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  58244. this._registerFunc = null;
  58245. }
  58246. this._connectedMesh = meshToConnectTo;
  58247. if (!this.spatialSound) {
  58248. this.spatialSound = true;
  58249. this._createSpatialParameters();
  58250. if (this.isPlaying && this.loop) {
  58251. this.stop();
  58252. this.play();
  58253. }
  58254. }
  58255. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  58256. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  58257. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  58258. };
  58259. Sound.prototype.detachFromMesh = function () {
  58260. if (this._connectedMesh && this._registerFunc) {
  58261. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  58262. this._registerFunc = null;
  58263. this._connectedMesh = null;
  58264. }
  58265. };
  58266. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  58267. if (!node.getBoundingInfo) {
  58268. return;
  58269. }
  58270. var mesh = node;
  58271. var boundingInfo = mesh.getBoundingInfo();
  58272. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  58273. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  58274. this._updateDirection();
  58275. }
  58276. };
  58277. Sound.prototype.clone = function () {
  58278. var _this = this;
  58279. if (!this._streaming) {
  58280. var setBufferAndRun = function () {
  58281. if (_this._isReadyToPlay) {
  58282. clonedSound._audioBuffer = _this.getAudioBuffer();
  58283. clonedSound._isReadyToPlay = true;
  58284. if (clonedSound.autoplay) {
  58285. clonedSound.play();
  58286. }
  58287. }
  58288. else {
  58289. window.setTimeout(setBufferAndRun, 300);
  58290. }
  58291. };
  58292. var currentOptions = {
  58293. autoplay: this.autoplay, loop: this.loop,
  58294. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  58295. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  58296. refDistance: this.refDistance, distanceModel: this.distanceModel
  58297. };
  58298. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  58299. if (this.useCustomAttenuation) {
  58300. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  58301. }
  58302. clonedSound.setPosition(this._position);
  58303. clonedSound.setPlaybackRate(this._playbackRate);
  58304. setBufferAndRun();
  58305. return clonedSound;
  58306. }
  58307. else {
  58308. return null;
  58309. }
  58310. };
  58311. Sound.prototype.getAudioBuffer = function () {
  58312. return this._audioBuffer;
  58313. };
  58314. Sound.prototype.serialize = function () {
  58315. var serializationObject = {
  58316. name: this.name,
  58317. url: this.name,
  58318. autoplay: this.autoplay,
  58319. loop: this.loop,
  58320. volume: this._volume,
  58321. spatialSound: this.spatialSound,
  58322. maxDistance: this.maxDistance,
  58323. rolloffFactor: this.rolloffFactor,
  58324. refDistance: this.refDistance,
  58325. distanceModel: this.distanceModel,
  58326. playbackRate: this._playbackRate,
  58327. panningModel: this._panningModel,
  58328. soundTrackId: this.soundTrackId
  58329. };
  58330. if (this.spatialSound) {
  58331. if (this._connectedMesh)
  58332. serializationObject.connectedMeshId = this._connectedMesh.id;
  58333. serializationObject.position = this._position.asArray();
  58334. serializationObject.refDistance = this.refDistance;
  58335. serializationObject.distanceModel = this.distanceModel;
  58336. serializationObject.isDirectional = this._isDirectional;
  58337. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  58338. serializationObject.coneInnerAngle = this._coneInnerAngle;
  58339. serializationObject.coneOuterAngle = this._coneOuterAngle;
  58340. serializationObject.coneOuterGain = this._coneOuterGain;
  58341. }
  58342. return serializationObject;
  58343. };
  58344. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  58345. var soundName = parsedSound.name;
  58346. var soundUrl;
  58347. if (parsedSound.url) {
  58348. soundUrl = rootUrl + parsedSound.url;
  58349. }
  58350. else {
  58351. soundUrl = rootUrl + soundName;
  58352. }
  58353. var options = {
  58354. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  58355. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  58356. rolloffFactor: parsedSound.rolloffFactor,
  58357. refDistance: parsedSound.refDistance,
  58358. distanceModel: parsedSound.distanceModel,
  58359. playbackRate: parsedSound.playbackRate
  58360. };
  58361. var newSound;
  58362. if (!sourceSound) {
  58363. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  58364. scene._addPendingData(newSound);
  58365. }
  58366. else {
  58367. var setBufferAndRun = function () {
  58368. if (sourceSound._isReadyToPlay) {
  58369. newSound._audioBuffer = sourceSound.getAudioBuffer();
  58370. newSound._isReadyToPlay = true;
  58371. if (newSound.autoplay) {
  58372. newSound.play();
  58373. }
  58374. }
  58375. else {
  58376. window.setTimeout(setBufferAndRun, 300);
  58377. }
  58378. };
  58379. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  58380. setBufferAndRun();
  58381. }
  58382. if (parsedSound.position) {
  58383. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  58384. newSound.setPosition(soundPosition);
  58385. }
  58386. if (parsedSound.isDirectional) {
  58387. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  58388. if (parsedSound.localDirectionToMesh) {
  58389. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  58390. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  58391. }
  58392. }
  58393. if (parsedSound.connectedMeshId) {
  58394. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  58395. if (connectedMesh) {
  58396. newSound.attachToMesh(connectedMesh);
  58397. }
  58398. }
  58399. return newSound;
  58400. };
  58401. return Sound;
  58402. }());
  58403. BABYLON.Sound = Sound;
  58404. })(BABYLON || (BABYLON = {}));
  58405. //# sourceMappingURL=babylon.sound.js.map
  58406. "use strict";
  58407. var BABYLON;
  58408. (function (BABYLON) {
  58409. var SoundTrack = /** @class */ (function () {
  58410. function SoundTrack(scene, options) {
  58411. this.id = -1;
  58412. this._isMainTrack = false;
  58413. this._isInitialized = false;
  58414. this._scene = scene;
  58415. this.soundCollection = new Array();
  58416. this._options = options;
  58417. if (!this._isMainTrack) {
  58418. this._scene.soundTracks.push(this);
  58419. this.id = this._scene.soundTracks.length - 1;
  58420. }
  58421. }
  58422. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  58423. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  58424. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  58425. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  58426. if (this._options) {
  58427. if (this._options.volume) {
  58428. this._outputAudioNode.gain.value = this._options.volume;
  58429. }
  58430. if (this._options.mainTrack) {
  58431. this._isMainTrack = this._options.mainTrack;
  58432. }
  58433. }
  58434. this._isInitialized = true;
  58435. }
  58436. };
  58437. SoundTrack.prototype.dispose = function () {
  58438. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  58439. if (this._connectedAnalyser) {
  58440. this._connectedAnalyser.stopDebugCanvas();
  58441. }
  58442. while (this.soundCollection.length) {
  58443. this.soundCollection[0].dispose();
  58444. }
  58445. if (this._outputAudioNode) {
  58446. this._outputAudioNode.disconnect();
  58447. }
  58448. this._outputAudioNode = null;
  58449. }
  58450. };
  58451. SoundTrack.prototype.AddSound = function (sound) {
  58452. if (!this._isInitialized) {
  58453. this._initializeSoundTrackAudioGraph();
  58454. }
  58455. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  58456. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  58457. }
  58458. if (sound.soundTrackId) {
  58459. if (sound.soundTrackId === -1) {
  58460. this._scene.mainSoundTrack.RemoveSound(sound);
  58461. }
  58462. else {
  58463. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  58464. }
  58465. }
  58466. this.soundCollection.push(sound);
  58467. sound.soundTrackId = this.id;
  58468. };
  58469. SoundTrack.prototype.RemoveSound = function (sound) {
  58470. var index = this.soundCollection.indexOf(sound);
  58471. if (index !== -1) {
  58472. this.soundCollection.splice(index, 1);
  58473. }
  58474. };
  58475. SoundTrack.prototype.setVolume = function (newVolume) {
  58476. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  58477. this._outputAudioNode.gain.value = newVolume;
  58478. }
  58479. };
  58480. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  58481. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58482. for (var i = 0; i < this.soundCollection.length; i++) {
  58483. this.soundCollection[i].switchPanningModelToHRTF();
  58484. }
  58485. }
  58486. };
  58487. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  58488. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  58489. for (var i = 0; i < this.soundCollection.length; i++) {
  58490. this.soundCollection[i].switchPanningModelToEqualPower();
  58491. }
  58492. }
  58493. };
  58494. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  58495. if (this._connectedAnalyser) {
  58496. this._connectedAnalyser.stopDebugCanvas();
  58497. }
  58498. this._connectedAnalyser = analyser;
  58499. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  58500. this._outputAudioNode.disconnect();
  58501. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  58502. }
  58503. };
  58504. return SoundTrack;
  58505. }());
  58506. BABYLON.SoundTrack = SoundTrack;
  58507. })(BABYLON || (BABYLON = {}));
  58508. //# sourceMappingURL=babylon.soundtrack.js.map
  58509. "use strict";
  58510. var BABYLON;
  58511. (function (BABYLON) {
  58512. var Analyser = /** @class */ (function () {
  58513. function Analyser(scene) {
  58514. this.SMOOTHING = 0.75;
  58515. this.FFT_SIZE = 512;
  58516. this.BARGRAPHAMPLITUDE = 256;
  58517. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  58518. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  58519. this._scene = scene;
  58520. this._audioEngine = BABYLON.Engine.audioEngine;
  58521. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  58522. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  58523. this._webAudioAnalyser.minDecibels = -140;
  58524. this._webAudioAnalyser.maxDecibels = 0;
  58525. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  58526. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  58527. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  58528. }
  58529. }
  58530. Analyser.prototype.getFrequencyBinCount = function () {
  58531. if (this._audioEngine.canUseWebAudio) {
  58532. return this._webAudioAnalyser.frequencyBinCount;
  58533. }
  58534. else {
  58535. return 0;
  58536. }
  58537. };
  58538. Analyser.prototype.getByteFrequencyData = function () {
  58539. if (this._audioEngine.canUseWebAudio) {
  58540. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  58541. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  58542. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  58543. }
  58544. return this._byteFreqs;
  58545. };
  58546. Analyser.prototype.getByteTimeDomainData = function () {
  58547. if (this._audioEngine.canUseWebAudio) {
  58548. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  58549. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  58550. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  58551. }
  58552. return this._byteTime;
  58553. };
  58554. Analyser.prototype.getFloatFrequencyData = function () {
  58555. if (this._audioEngine.canUseWebAudio) {
  58556. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  58557. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  58558. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  58559. }
  58560. return this._floatFreqs;
  58561. };
  58562. Analyser.prototype.drawDebugCanvas = function () {
  58563. var _this = this;
  58564. if (this._audioEngine.canUseWebAudio) {
  58565. if (!this._debugCanvas) {
  58566. this._debugCanvas = document.createElement("canvas");
  58567. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  58568. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  58569. this._debugCanvas.style.position = "absolute";
  58570. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  58571. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  58572. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  58573. document.body.appendChild(this._debugCanvas);
  58574. this._registerFunc = function () {
  58575. _this.drawDebugCanvas();
  58576. };
  58577. this._scene.registerBeforeRender(this._registerFunc);
  58578. }
  58579. if (this._registerFunc && this._debugCanvasContext) {
  58580. var workingArray = this.getByteFrequencyData();
  58581. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  58582. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  58583. // Draw the frequency domain chart.
  58584. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  58585. var value = workingArray[i];
  58586. var percent = value / this.BARGRAPHAMPLITUDE;
  58587. var height = this.DEBUGCANVASSIZE.height * percent;
  58588. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  58589. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  58590. var hue = i / this.getFrequencyBinCount() * 360;
  58591. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  58592. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  58593. }
  58594. }
  58595. }
  58596. };
  58597. Analyser.prototype.stopDebugCanvas = function () {
  58598. if (this._debugCanvas) {
  58599. if (this._registerFunc) {
  58600. this._scene.unregisterBeforeRender(this._registerFunc);
  58601. this._registerFunc = null;
  58602. }
  58603. document.body.removeChild(this._debugCanvas);
  58604. this._debugCanvas = null;
  58605. this._debugCanvasContext = null;
  58606. }
  58607. };
  58608. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  58609. if (this._audioEngine.canUseWebAudio) {
  58610. inputAudioNode.connect(this._webAudioAnalyser);
  58611. this._webAudioAnalyser.connect(outputAudioNode);
  58612. }
  58613. };
  58614. Analyser.prototype.dispose = function () {
  58615. if (this._audioEngine.canUseWebAudio) {
  58616. this._webAudioAnalyser.disconnect();
  58617. }
  58618. };
  58619. return Analyser;
  58620. }());
  58621. BABYLON.Analyser = Analyser;
  58622. })(BABYLON || (BABYLON = {}));
  58623. //# sourceMappingURL=babylon.analyser.js.map
  58624. "use strict";
  58625. var BABYLON;
  58626. (function (BABYLON) {
  58627. var CubeTexture = /** @class */ (function (_super) {
  58628. __extends(CubeTexture, _super);
  58629. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  58630. if (extensions === void 0) { extensions = null; }
  58631. if (noMipmap === void 0) { noMipmap = false; }
  58632. if (files === void 0) { files = null; }
  58633. if (onLoad === void 0) { onLoad = null; }
  58634. if (onError === void 0) { onError = null; }
  58635. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  58636. if (prefiltered === void 0) { prefiltered = false; }
  58637. if (forcedExtension === void 0) { forcedExtension = null; }
  58638. var _this = _super.call(this, scene) || this;
  58639. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  58640. /**
  58641. * Gets or sets the center of the bounding box associated with the cube texture
  58642. * It must define where the camera used to render the texture was set
  58643. */
  58644. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  58645. _this.name = rootUrl;
  58646. _this.url = rootUrl;
  58647. _this._noMipmap = noMipmap;
  58648. _this.hasAlpha = false;
  58649. _this._format = format;
  58650. _this._prefiltered = prefiltered;
  58651. _this.isCube = true;
  58652. _this._textureMatrix = BABYLON.Matrix.Identity();
  58653. if (prefiltered) {
  58654. _this.gammaSpace = false;
  58655. }
  58656. if (!rootUrl && !files) {
  58657. return _this;
  58658. }
  58659. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  58660. var lastDot = rootUrl.lastIndexOf(".");
  58661. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  58662. var isDDS = (extension === ".dds");
  58663. if (!files) {
  58664. if (!isDDS && !extensions) {
  58665. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  58666. }
  58667. files = [];
  58668. if (extensions) {
  58669. for (var index = 0; index < extensions.length; index++) {
  58670. files.push(rootUrl + extensions[index]);
  58671. }
  58672. }
  58673. }
  58674. _this._files = files;
  58675. if (!_this._texture) {
  58676. if (!scene.useDelayedTextureLoading) {
  58677. if (prefiltered) {
  58678. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  58679. }
  58680. else {
  58681. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  58682. }
  58683. }
  58684. else {
  58685. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  58686. }
  58687. }
  58688. else if (onLoad) {
  58689. if (_this._texture.isReady) {
  58690. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  58691. }
  58692. else {
  58693. _this._texture.onLoadedObservable.add(onLoad);
  58694. }
  58695. }
  58696. return _this;
  58697. }
  58698. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  58699. get: function () {
  58700. return this._boundingBoxSize;
  58701. },
  58702. /**
  58703. * Gets or sets the size of the bounding box associated with the cube texture
  58704. * When defined, the cubemap will switch to local mode
  58705. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  58706. * @example https://www.babylonjs-playground.com/#RNASML
  58707. */
  58708. set: function (value) {
  58709. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  58710. return;
  58711. }
  58712. this._boundingBoxSize = value;
  58713. var scene = this.getScene();
  58714. if (scene) {
  58715. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  58716. }
  58717. },
  58718. enumerable: true,
  58719. configurable: true
  58720. });
  58721. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  58722. var rootUrlKey = "";
  58723. files.forEach(function (url) { return rootUrlKey += url; });
  58724. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  58725. };
  58726. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  58727. if (forcedExtension === void 0) { forcedExtension = null; }
  58728. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  58729. };
  58730. // Methods
  58731. CubeTexture.prototype.delayLoad = function () {
  58732. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  58733. return;
  58734. }
  58735. var scene = this.getScene();
  58736. if (!scene) {
  58737. return;
  58738. }
  58739. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  58740. this._texture = this._getFromCache(this.url, this._noMipmap);
  58741. if (!this._texture) {
  58742. if (this._prefiltered) {
  58743. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  58744. }
  58745. else {
  58746. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  58747. }
  58748. }
  58749. };
  58750. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  58751. return this._textureMatrix;
  58752. };
  58753. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  58754. this._textureMatrix = value;
  58755. };
  58756. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  58757. var texture = BABYLON.SerializationHelper.Parse(function () {
  58758. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  58759. }, parsedTexture, scene);
  58760. // Local Cubemaps
  58761. if (parsedTexture.boundingBoxPosition) {
  58762. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  58763. }
  58764. if (parsedTexture.boundingBoxSize) {
  58765. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  58766. }
  58767. // Animations
  58768. if (parsedTexture.animations) {
  58769. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  58770. var parsedAnimation = parsedTexture.animations[animationIndex];
  58771. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  58772. }
  58773. }
  58774. return texture;
  58775. };
  58776. CubeTexture.prototype.clone = function () {
  58777. var _this = this;
  58778. return BABYLON.SerializationHelper.Clone(function () {
  58779. var scene = _this.getScene();
  58780. if (!scene) {
  58781. return _this;
  58782. }
  58783. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  58784. }, this);
  58785. };
  58786. return CubeTexture;
  58787. }(BABYLON.BaseTexture));
  58788. BABYLON.CubeTexture = CubeTexture;
  58789. })(BABYLON || (BABYLON = {}));
  58790. //# sourceMappingURL=babylon.cubeTexture.js.map
  58791. "use strict";
  58792. var BABYLON;
  58793. (function (BABYLON) {
  58794. var RenderTargetTexture = /** @class */ (function (_super) {
  58795. __extends(RenderTargetTexture, _super);
  58796. /**
  58797. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  58798. * or used a shadow, depth texture...
  58799. * @param name The friendly name of the texture
  58800. * @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)
  58801. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  58802. * @param generateMipMaps True if mip maps need to be generated after render.
  58803. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  58804. * @param type The type of the buffer in the RTT (int, half float, float...)
  58805. * @param isCube True if a cube texture needs to be created
  58806. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  58807. * @param generateDepthBuffer True to generate a depth buffer
  58808. * @param generateStencilBuffer True to generate a stencil buffer
  58809. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  58810. */
  58811. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  58812. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  58813. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  58814. if (isCube === void 0) { isCube = false; }
  58815. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  58816. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  58817. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  58818. if (isMulti === void 0) { isMulti = false; }
  58819. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  58820. _this.isCube = isCube;
  58821. /**
  58822. * Use this list to define the list of mesh you want to render.
  58823. */
  58824. _this.renderList = new Array();
  58825. _this.renderParticles = true;
  58826. _this.renderSprites = false;
  58827. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  58828. _this.ignoreCameraViewport = false;
  58829. // Events
  58830. /**
  58831. * An event triggered when the texture is unbind.
  58832. * @type {BABYLON.Observable}
  58833. */
  58834. _this.onBeforeBindObservable = new BABYLON.Observable();
  58835. /**
  58836. * An event triggered when the texture is unbind.
  58837. * @type {BABYLON.Observable}
  58838. */
  58839. _this.onAfterUnbindObservable = new BABYLON.Observable();
  58840. /**
  58841. * An event triggered before rendering the texture
  58842. * @type {BABYLON.Observable}
  58843. */
  58844. _this.onBeforeRenderObservable = new BABYLON.Observable();
  58845. /**
  58846. * An event triggered after rendering the texture
  58847. * @type {BABYLON.Observable}
  58848. */
  58849. _this.onAfterRenderObservable = new BABYLON.Observable();
  58850. /**
  58851. * An event triggered after the texture clear
  58852. * @type {BABYLON.Observable}
  58853. */
  58854. _this.onClearObservable = new BABYLON.Observable();
  58855. _this._currentRefreshId = -1;
  58856. _this._refreshRate = 1;
  58857. _this._samples = 1;
  58858. /**
  58859. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  58860. * It must define where the camera used to render the texture is set
  58861. */
  58862. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  58863. scene = _this.getScene();
  58864. if (!scene) {
  58865. return _this;
  58866. }
  58867. _this._engine = scene.getEngine();
  58868. _this.name = name;
  58869. _this.isRenderTarget = true;
  58870. _this._initialSizeParameter = size;
  58871. _this._processSizeParameter(size);
  58872. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  58873. });
  58874. _this._generateMipMaps = generateMipMaps ? true : false;
  58875. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  58876. // Rendering groups
  58877. _this._renderingManager = new BABYLON.RenderingManager(scene);
  58878. if (isMulti) {
  58879. return _this;
  58880. }
  58881. _this._renderTargetOptions = {
  58882. generateMipMaps: generateMipMaps,
  58883. type: type,
  58884. samplingMode: samplingMode,
  58885. generateDepthBuffer: generateDepthBuffer,
  58886. generateStencilBuffer: generateStencilBuffer
  58887. };
  58888. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  58889. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58890. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  58891. }
  58892. if (isCube) {
  58893. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  58894. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  58895. _this._textureMatrix = BABYLON.Matrix.Identity();
  58896. }
  58897. else {
  58898. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  58899. }
  58900. return _this;
  58901. }
  58902. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  58903. get: function () {
  58904. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  58905. },
  58906. enumerable: true,
  58907. configurable: true
  58908. });
  58909. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  58910. get: function () {
  58911. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  58912. },
  58913. enumerable: true,
  58914. configurable: true
  58915. });
  58916. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  58917. get: function () {
  58918. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  58919. },
  58920. enumerable: true,
  58921. configurable: true
  58922. });
  58923. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  58924. set: function (callback) {
  58925. if (this._onAfterUnbindObserver) {
  58926. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  58927. }
  58928. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  58929. },
  58930. enumerable: true,
  58931. configurable: true
  58932. });
  58933. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  58934. set: function (callback) {
  58935. if (this._onBeforeRenderObserver) {
  58936. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  58937. }
  58938. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  58939. },
  58940. enumerable: true,
  58941. configurable: true
  58942. });
  58943. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  58944. set: function (callback) {
  58945. if (this._onAfterRenderObserver) {
  58946. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  58947. }
  58948. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  58949. },
  58950. enumerable: true,
  58951. configurable: true
  58952. });
  58953. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  58954. set: function (callback) {
  58955. if (this._onClearObserver) {
  58956. this.onClearObservable.remove(this._onClearObserver);
  58957. }
  58958. this._onClearObserver = this.onClearObservable.add(callback);
  58959. },
  58960. enumerable: true,
  58961. configurable: true
  58962. });
  58963. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  58964. get: function () {
  58965. return this._renderTargetOptions;
  58966. },
  58967. enumerable: true,
  58968. configurable: true
  58969. });
  58970. RenderTargetTexture.prototype._onRatioRescale = function () {
  58971. if (this._sizeRatio) {
  58972. this.resize(this._initialSizeParameter);
  58973. }
  58974. };
  58975. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  58976. get: function () {
  58977. return this._boundingBoxSize;
  58978. },
  58979. /**
  58980. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  58981. * When defined, the cubemap will switch to local mode
  58982. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  58983. * @example https://www.babylonjs-playground.com/#RNASML
  58984. */
  58985. set: function (value) {
  58986. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  58987. return;
  58988. }
  58989. this._boundingBoxSize = value;
  58990. var scene = this.getScene();
  58991. if (scene) {
  58992. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  58993. }
  58994. },
  58995. enumerable: true,
  58996. configurable: true
  58997. });
  58998. /**
  58999. * Creates a depth stencil texture.
  59000. * This is only available in WebGL 2 or with the depth texture extension available.
  59001. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  59002. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  59003. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  59004. */
  59005. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  59006. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  59007. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  59008. if (generateStencil === void 0) { generateStencil = false; }
  59009. if (!this.getScene()) {
  59010. return;
  59011. }
  59012. var engine = this.getScene().getEngine();
  59013. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  59014. bilinearFiltering: bilinearFiltering,
  59015. comparisonFunction: comparisonFunction,
  59016. generateStencil: generateStencil,
  59017. isCube: this.isCube
  59018. });
  59019. engine.setFrameBufferDepthStencilTexture(this);
  59020. };
  59021. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  59022. if (size.ratio) {
  59023. this._sizeRatio = size.ratio;
  59024. this._size = {
  59025. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  59026. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  59027. };
  59028. }
  59029. else {
  59030. this._size = size;
  59031. }
  59032. };
  59033. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  59034. get: function () {
  59035. return this._samples;
  59036. },
  59037. set: function (value) {
  59038. if (this._samples === value) {
  59039. return;
  59040. }
  59041. var scene = this.getScene();
  59042. if (!scene) {
  59043. return;
  59044. }
  59045. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  59046. },
  59047. enumerable: true,
  59048. configurable: true
  59049. });
  59050. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  59051. this._currentRefreshId = -1;
  59052. };
  59053. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  59054. get: function () {
  59055. return this._refreshRate;
  59056. },
  59057. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  59058. set: function (value) {
  59059. this._refreshRate = value;
  59060. this.resetRefreshCounter();
  59061. },
  59062. enumerable: true,
  59063. configurable: true
  59064. });
  59065. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  59066. if (!this._postProcessManager) {
  59067. var scene = this.getScene();
  59068. if (!scene) {
  59069. return;
  59070. }
  59071. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  59072. this._postProcesses = new Array();
  59073. }
  59074. this._postProcesses.push(postProcess);
  59075. this._postProcesses[0].autoClear = false;
  59076. };
  59077. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  59078. if (!this._postProcesses) {
  59079. return;
  59080. }
  59081. if (dispose) {
  59082. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  59083. var postProcess = _a[_i];
  59084. postProcess.dispose();
  59085. }
  59086. }
  59087. this._postProcesses = [];
  59088. };
  59089. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  59090. if (!this._postProcesses) {
  59091. return;
  59092. }
  59093. var index = this._postProcesses.indexOf(postProcess);
  59094. if (index === -1) {
  59095. return;
  59096. }
  59097. this._postProcesses.splice(index, 1);
  59098. if (this._postProcesses.length > 0) {
  59099. this._postProcesses[0].autoClear = false;
  59100. }
  59101. };
  59102. RenderTargetTexture.prototype._shouldRender = function () {
  59103. if (this._currentRefreshId === -1) {
  59104. this._currentRefreshId = 1;
  59105. return true;
  59106. }
  59107. if (this.refreshRate === this._currentRefreshId) {
  59108. this._currentRefreshId = 1;
  59109. return true;
  59110. }
  59111. this._currentRefreshId++;
  59112. return false;
  59113. };
  59114. RenderTargetTexture.prototype.getRenderSize = function () {
  59115. if (this._size.width) {
  59116. return this._size.width;
  59117. }
  59118. return this._size;
  59119. };
  59120. RenderTargetTexture.prototype.getRenderWidth = function () {
  59121. if (this._size.width) {
  59122. return this._size.width;
  59123. }
  59124. return this._size;
  59125. };
  59126. RenderTargetTexture.prototype.getRenderHeight = function () {
  59127. if (this._size.width) {
  59128. return this._size.height;
  59129. }
  59130. return this._size;
  59131. };
  59132. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  59133. get: function () {
  59134. return true;
  59135. },
  59136. enumerable: true,
  59137. configurable: true
  59138. });
  59139. RenderTargetTexture.prototype.scale = function (ratio) {
  59140. var newSize = this.getRenderSize() * ratio;
  59141. this.resize(newSize);
  59142. };
  59143. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  59144. if (this.isCube) {
  59145. return this._textureMatrix;
  59146. }
  59147. return _super.prototype.getReflectionTextureMatrix.call(this);
  59148. };
  59149. RenderTargetTexture.prototype.resize = function (size) {
  59150. this.releaseInternalTexture();
  59151. var scene = this.getScene();
  59152. if (!scene) {
  59153. return;
  59154. }
  59155. this._processSizeParameter(size);
  59156. if (this.isCube) {
  59157. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  59158. }
  59159. else {
  59160. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  59161. }
  59162. };
  59163. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  59164. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  59165. if (dumpForDebug === void 0) { dumpForDebug = false; }
  59166. var scene = this.getScene();
  59167. if (!scene) {
  59168. return;
  59169. }
  59170. var engine = scene.getEngine();
  59171. if (this.useCameraPostProcesses !== undefined) {
  59172. useCameraPostProcess = this.useCameraPostProcesses;
  59173. }
  59174. if (this._waitingRenderList) {
  59175. this.renderList = [];
  59176. for (var index = 0; index < this._waitingRenderList.length; index++) {
  59177. var id = this._waitingRenderList[index];
  59178. var mesh_1 = scene.getMeshByID(id);
  59179. if (mesh_1) {
  59180. this.renderList.push(mesh_1);
  59181. }
  59182. }
  59183. delete this._waitingRenderList;
  59184. }
  59185. // Is predicate defined?
  59186. if (this.renderListPredicate) {
  59187. if (this.renderList) {
  59188. this.renderList.splice(0); // Clear previous renderList
  59189. }
  59190. else {
  59191. this.renderList = [];
  59192. }
  59193. var scene = this.getScene();
  59194. if (!scene) {
  59195. return;
  59196. }
  59197. var sceneMeshes = scene.meshes;
  59198. for (var index = 0; index < sceneMeshes.length; index++) {
  59199. var mesh = sceneMeshes[index];
  59200. if (this.renderListPredicate(mesh)) {
  59201. this.renderList.push(mesh);
  59202. }
  59203. }
  59204. }
  59205. this.onBeforeBindObservable.notifyObservers(this);
  59206. // Set custom projection.
  59207. // Needs to be before binding to prevent changing the aspect ratio.
  59208. var camera;
  59209. if (this.activeCamera) {
  59210. camera = this.activeCamera;
  59211. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  59212. if (this.activeCamera !== scene.activeCamera) {
  59213. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  59214. }
  59215. }
  59216. else {
  59217. camera = scene.activeCamera;
  59218. if (camera) {
  59219. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  59220. }
  59221. }
  59222. // Prepare renderingManager
  59223. this._renderingManager.reset();
  59224. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  59225. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  59226. var sceneRenderId = scene.getRenderId();
  59227. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  59228. var mesh = currentRenderList[meshIndex];
  59229. if (mesh) {
  59230. if (!mesh.isReady(this.refreshRate === 0)) {
  59231. this.resetRefreshCounter();
  59232. continue;
  59233. }
  59234. mesh._preActivateForIntermediateRendering(sceneRenderId);
  59235. var isMasked = void 0;
  59236. if (!this.renderList && camera) {
  59237. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  59238. }
  59239. else {
  59240. isMasked = false;
  59241. }
  59242. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  59243. mesh._activate(sceneRenderId);
  59244. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  59245. var subMesh = mesh.subMeshes[subIndex];
  59246. scene._activeIndices.addCount(subMesh.indexCount, false);
  59247. this._renderingManager.dispatch(subMesh, mesh);
  59248. }
  59249. }
  59250. }
  59251. }
  59252. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  59253. var particleSystem = scene.particleSystems[particleIndex];
  59254. var emitter = particleSystem.emitter;
  59255. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  59256. continue;
  59257. }
  59258. if (currentRenderList.indexOf(emitter) >= 0) {
  59259. this._renderingManager.dispatchParticles(particleSystem);
  59260. }
  59261. }
  59262. if (this.isCube) {
  59263. for (var face = 0; face < 6; face++) {
  59264. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  59265. scene.incrementRenderId();
  59266. scene.resetCachedMaterial();
  59267. }
  59268. }
  59269. else {
  59270. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  59271. }
  59272. this.onAfterUnbindObservable.notifyObservers(this);
  59273. if (scene.activeCamera) {
  59274. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  59275. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  59276. }
  59277. engine.setViewport(scene.activeCamera.viewport);
  59278. }
  59279. scene.resetCachedMaterial();
  59280. };
  59281. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  59282. var minimum = 128;
  59283. var x = renderDimension * scale;
  59284. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  59285. // Ensure we don't exceed the render dimension (while staying POT)
  59286. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  59287. };
  59288. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  59289. var _this = this;
  59290. if (!this._texture) {
  59291. return;
  59292. }
  59293. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  59294. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  59295. });
  59296. };
  59297. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  59298. var scene = this.getScene();
  59299. if (!scene) {
  59300. return;
  59301. }
  59302. var engine = scene.getEngine();
  59303. if (!this._texture) {
  59304. return;
  59305. }
  59306. // Bind
  59307. if (this._postProcessManager) {
  59308. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  59309. }
  59310. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  59311. if (this._texture) {
  59312. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  59313. }
  59314. }
  59315. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  59316. // Clear
  59317. if (this.onClearObservable.hasObservers()) {
  59318. this.onClearObservable.notifyObservers(engine);
  59319. }
  59320. else {
  59321. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  59322. }
  59323. if (!this._doNotChangeAspectRatio) {
  59324. scene.updateTransformMatrix(true);
  59325. }
  59326. // Render
  59327. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  59328. if (this._postProcessManager) {
  59329. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  59330. }
  59331. else if (useCameraPostProcess) {
  59332. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  59333. }
  59334. if (!this._doNotChangeAspectRatio) {
  59335. scene.updateTransformMatrix(true);
  59336. }
  59337. // Dump ?
  59338. if (dumpForDebug) {
  59339. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  59340. }
  59341. // Unbind
  59342. if (!this.isCube || faceIndex === 5) {
  59343. if (this.isCube) {
  59344. if (faceIndex === 5) {
  59345. engine.generateMipMapsForCubemap(this._texture);
  59346. }
  59347. }
  59348. this.unbindFrameBuffer(engine, faceIndex);
  59349. }
  59350. else {
  59351. this.onAfterRenderObservable.notifyObservers(faceIndex);
  59352. }
  59353. };
  59354. /**
  59355. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  59356. * This allowed control for front to back rendering or reversly depending of the special needs.
  59357. *
  59358. * @param renderingGroupId The rendering group id corresponding to its index
  59359. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  59360. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  59361. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  59362. */
  59363. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  59364. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  59365. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  59366. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  59367. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  59368. };
  59369. /**
  59370. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  59371. *
  59372. * @param renderingGroupId The rendering group id corresponding to its index
  59373. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  59374. */
  59375. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  59376. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  59377. };
  59378. RenderTargetTexture.prototype.clone = function () {
  59379. var textureSize = this.getSize();
  59380. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer);
  59381. // Base texture
  59382. newTexture.hasAlpha = this.hasAlpha;
  59383. newTexture.level = this.level;
  59384. // RenderTarget Texture
  59385. newTexture.coordinatesMode = this.coordinatesMode;
  59386. if (this.renderList) {
  59387. newTexture.renderList = this.renderList.slice(0);
  59388. }
  59389. return newTexture;
  59390. };
  59391. RenderTargetTexture.prototype.serialize = function () {
  59392. if (!this.name) {
  59393. return null;
  59394. }
  59395. var serializationObject = _super.prototype.serialize.call(this);
  59396. serializationObject.renderTargetSize = this.getRenderSize();
  59397. serializationObject.renderList = [];
  59398. if (this.renderList) {
  59399. for (var index = 0; index < this.renderList.length; index++) {
  59400. serializationObject.renderList.push(this.renderList[index].id);
  59401. }
  59402. }
  59403. return serializationObject;
  59404. };
  59405. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  59406. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  59407. var objBuffer = this.getInternalTexture();
  59408. var scene = this.getScene();
  59409. if (objBuffer && scene) {
  59410. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  59411. }
  59412. };
  59413. RenderTargetTexture.prototype.dispose = function () {
  59414. if (this._postProcessManager) {
  59415. this._postProcessManager.dispose();
  59416. this._postProcessManager = null;
  59417. }
  59418. this.clearPostProcesses(true);
  59419. if (this._resizeObserver) {
  59420. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  59421. this._resizeObserver = null;
  59422. }
  59423. this.renderList = null;
  59424. // Remove from custom render targets
  59425. var scene = this.getScene();
  59426. if (!scene) {
  59427. return;
  59428. }
  59429. var index = scene.customRenderTargets.indexOf(this);
  59430. if (index >= 0) {
  59431. scene.customRenderTargets.splice(index, 1);
  59432. }
  59433. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  59434. var camera = _a[_i];
  59435. index = camera.customRenderTargets.indexOf(this);
  59436. if (index >= 0) {
  59437. camera.customRenderTargets.splice(index, 1);
  59438. }
  59439. }
  59440. _super.prototype.dispose.call(this);
  59441. };
  59442. RenderTargetTexture.prototype._rebuild = function () {
  59443. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  59444. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  59445. }
  59446. if (this._postProcessManager) {
  59447. this._postProcessManager._rebuild();
  59448. }
  59449. };
  59450. /**
  59451. * Clear the info related to rendering groups preventing retention point in material dispose.
  59452. */
  59453. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  59454. if (this._renderingManager) {
  59455. this._renderingManager.freeRenderingGroups();
  59456. }
  59457. };
  59458. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  59459. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  59460. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  59461. return RenderTargetTexture;
  59462. }(BABYLON.Texture));
  59463. BABYLON.RenderTargetTexture = RenderTargetTexture;
  59464. })(BABYLON || (BABYLON = {}));
  59465. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  59466. "use strict";
  59467. var BABYLON;
  59468. (function (BABYLON) {
  59469. ;
  59470. var MultiRenderTarget = /** @class */ (function (_super) {
  59471. __extends(MultiRenderTarget, _super);
  59472. function MultiRenderTarget(name, size, count, scene, options) {
  59473. var _this = this;
  59474. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  59475. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  59476. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  59477. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  59478. _this._engine = scene.getEngine();
  59479. if (!_this.isSupported) {
  59480. _this.dispose();
  59481. return;
  59482. }
  59483. var types = [];
  59484. var samplingModes = [];
  59485. for (var i = 0; i < count; i++) {
  59486. if (options && options.types && options.types[i] !== undefined) {
  59487. types.push(options.types[i]);
  59488. }
  59489. else {
  59490. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  59491. }
  59492. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  59493. samplingModes.push(options.samplingModes[i]);
  59494. }
  59495. else {
  59496. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  59497. }
  59498. }
  59499. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  59500. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  59501. _this._size = size;
  59502. _this._multiRenderTargetOptions = {
  59503. samplingModes: samplingModes,
  59504. generateMipMaps: generateMipMaps,
  59505. generateDepthBuffer: generateDepthBuffer,
  59506. generateStencilBuffer: generateStencilBuffer,
  59507. generateDepthTexture: generateDepthTexture,
  59508. types: types,
  59509. textureCount: count
  59510. };
  59511. _this._createInternalTextures();
  59512. _this._createTextures();
  59513. return _this;
  59514. }
  59515. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  59516. get: function () {
  59517. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  59518. },
  59519. enumerable: true,
  59520. configurable: true
  59521. });
  59522. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  59523. get: function () {
  59524. return this._textures;
  59525. },
  59526. enumerable: true,
  59527. configurable: true
  59528. });
  59529. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  59530. get: function () {
  59531. return this._textures[this._textures.length - 1];
  59532. },
  59533. enumerable: true,
  59534. configurable: true
  59535. });
  59536. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  59537. set: function (wrap) {
  59538. if (this._textures) {
  59539. for (var i = 0; i < this._textures.length; i++) {
  59540. this._textures[i].wrapU = wrap;
  59541. }
  59542. }
  59543. },
  59544. enumerable: true,
  59545. configurable: true
  59546. });
  59547. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  59548. set: function (wrap) {
  59549. if (this._textures) {
  59550. for (var i = 0; i < this._textures.length; i++) {
  59551. this._textures[i].wrapV = wrap;
  59552. }
  59553. }
  59554. },
  59555. enumerable: true,
  59556. configurable: true
  59557. });
  59558. MultiRenderTarget.prototype._rebuild = function () {
  59559. this.releaseInternalTextures();
  59560. this._createInternalTextures();
  59561. for (var i = 0; i < this._internalTextures.length; i++) {
  59562. var texture = this._textures[i];
  59563. texture._texture = this._internalTextures[i];
  59564. }
  59565. // Keeps references to frame buffer and stencil/depth buffer
  59566. this._texture = this._internalTextures[0];
  59567. };
  59568. MultiRenderTarget.prototype._createInternalTextures = function () {
  59569. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  59570. };
  59571. MultiRenderTarget.prototype._createTextures = function () {
  59572. this._textures = [];
  59573. for (var i = 0; i < this._internalTextures.length; i++) {
  59574. var texture = new BABYLON.Texture(null, this.getScene());
  59575. texture._texture = this._internalTextures[i];
  59576. this._textures.push(texture);
  59577. }
  59578. // Keeps references to frame buffer and stencil/depth buffer
  59579. this._texture = this._internalTextures[0];
  59580. };
  59581. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  59582. get: function () {
  59583. return this._samples;
  59584. },
  59585. set: function (value) {
  59586. if (this._samples === value) {
  59587. return;
  59588. }
  59589. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  59590. },
  59591. enumerable: true,
  59592. configurable: true
  59593. });
  59594. MultiRenderTarget.prototype.resize = function (size) {
  59595. this.releaseInternalTextures();
  59596. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  59597. this._createInternalTextures();
  59598. };
  59599. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  59600. var _this = this;
  59601. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  59602. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  59603. });
  59604. };
  59605. MultiRenderTarget.prototype.dispose = function () {
  59606. this.releaseInternalTextures();
  59607. _super.prototype.dispose.call(this);
  59608. };
  59609. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  59610. if (!this._internalTextures) {
  59611. return;
  59612. }
  59613. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  59614. if (this._internalTextures[i] !== undefined) {
  59615. this._internalTextures[i].dispose();
  59616. this._internalTextures.splice(i, 1);
  59617. }
  59618. }
  59619. };
  59620. return MultiRenderTarget;
  59621. }(BABYLON.RenderTargetTexture));
  59622. BABYLON.MultiRenderTarget = MultiRenderTarget;
  59623. })(BABYLON || (BABYLON = {}));
  59624. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  59625. "use strict";
  59626. var BABYLON;
  59627. (function (BABYLON) {
  59628. var MirrorTexture = /** @class */ (function (_super) {
  59629. __extends(MirrorTexture, _super);
  59630. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  59631. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  59632. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  59633. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  59634. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  59635. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  59636. _this._transformMatrix = BABYLON.Matrix.Zero();
  59637. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  59638. _this._adaptiveBlurKernel = 0;
  59639. _this._blurKernelX = 0;
  59640. _this._blurKernelY = 0;
  59641. _this._blurRatio = 1.0;
  59642. _this.ignoreCameraViewport = true;
  59643. _this.onBeforeRenderObservable.add(function () {
  59644. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  59645. _this._savedViewMatrix = scene.getViewMatrix();
  59646. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  59647. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  59648. scene.clipPlane = _this.mirrorPlane;
  59649. scene.getEngine().cullBackFaces = false;
  59650. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  59651. });
  59652. _this.onAfterRenderObservable.add(function () {
  59653. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  59654. scene.getEngine().cullBackFaces = true;
  59655. scene._mirroredCameraPosition = null;
  59656. delete scene.clipPlane;
  59657. });
  59658. return _this;
  59659. }
  59660. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  59661. get: function () {
  59662. return this._blurRatio;
  59663. },
  59664. set: function (value) {
  59665. if (this._blurRatio === value) {
  59666. return;
  59667. }
  59668. this._blurRatio = value;
  59669. this._preparePostProcesses();
  59670. },
  59671. enumerable: true,
  59672. configurable: true
  59673. });
  59674. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  59675. set: function (value) {
  59676. this._adaptiveBlurKernel = value;
  59677. this._autoComputeBlurKernel();
  59678. },
  59679. enumerable: true,
  59680. configurable: true
  59681. });
  59682. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  59683. set: function (value) {
  59684. this.blurKernelX = value;
  59685. this.blurKernelY = value;
  59686. },
  59687. enumerable: true,
  59688. configurable: true
  59689. });
  59690. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  59691. get: function () {
  59692. return this._blurKernelX;
  59693. },
  59694. set: function (value) {
  59695. if (this._blurKernelX === value) {
  59696. return;
  59697. }
  59698. this._blurKernelX = value;
  59699. this._preparePostProcesses();
  59700. },
  59701. enumerable: true,
  59702. configurable: true
  59703. });
  59704. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  59705. get: function () {
  59706. return this._blurKernelY;
  59707. },
  59708. set: function (value) {
  59709. if (this._blurKernelY === value) {
  59710. return;
  59711. }
  59712. this._blurKernelY = value;
  59713. this._preparePostProcesses();
  59714. },
  59715. enumerable: true,
  59716. configurable: true
  59717. });
  59718. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  59719. var engine = this.getScene().getEngine();
  59720. var dw = this.getRenderWidth() / engine.getRenderWidth();
  59721. var dh = this.getRenderHeight() / engine.getRenderHeight();
  59722. this.blurKernelX = this._adaptiveBlurKernel * dw;
  59723. this.blurKernelY = this._adaptiveBlurKernel * dh;
  59724. };
  59725. MirrorTexture.prototype._onRatioRescale = function () {
  59726. if (this._sizeRatio) {
  59727. this.resize(this._initialSizeParameter);
  59728. if (!this._adaptiveBlurKernel) {
  59729. this._preparePostProcesses();
  59730. }
  59731. }
  59732. if (this._adaptiveBlurKernel) {
  59733. this._autoComputeBlurKernel();
  59734. }
  59735. };
  59736. MirrorTexture.prototype._preparePostProcesses = function () {
  59737. this.clearPostProcesses(true);
  59738. if (this._blurKernelX && this._blurKernelY) {
  59739. var engine = this.getScene().getEngine();
  59740. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  59741. 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);
  59742. this._blurX.autoClear = false;
  59743. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  59744. this._blurX.inputTexture = this._texture;
  59745. }
  59746. else {
  59747. this._blurX.alwaysForcePOT = true;
  59748. }
  59749. 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);
  59750. this._blurY.autoClear = false;
  59751. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  59752. this.addPostProcess(this._blurX);
  59753. this.addPostProcess(this._blurY);
  59754. }
  59755. else {
  59756. if (this._blurY) {
  59757. this.removePostProcess(this._blurY);
  59758. this._blurY.dispose();
  59759. this._blurY = null;
  59760. }
  59761. if (this._blurX) {
  59762. this.removePostProcess(this._blurX);
  59763. this._blurX.dispose();
  59764. this._blurX = null;
  59765. }
  59766. }
  59767. };
  59768. MirrorTexture.prototype.clone = function () {
  59769. var scene = this.getScene();
  59770. if (!scene) {
  59771. return this;
  59772. }
  59773. var textureSize = this.getSize();
  59774. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  59775. // Base texture
  59776. newTexture.hasAlpha = this.hasAlpha;
  59777. newTexture.level = this.level;
  59778. // Mirror Texture
  59779. newTexture.mirrorPlane = this.mirrorPlane.clone();
  59780. if (this.renderList) {
  59781. newTexture.renderList = this.renderList.slice(0);
  59782. }
  59783. return newTexture;
  59784. };
  59785. MirrorTexture.prototype.serialize = function () {
  59786. if (!this.name) {
  59787. return null;
  59788. }
  59789. var serializationObject = _super.prototype.serialize.call(this);
  59790. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  59791. return serializationObject;
  59792. };
  59793. return MirrorTexture;
  59794. }(BABYLON.RenderTargetTexture));
  59795. BABYLON.MirrorTexture = MirrorTexture;
  59796. })(BABYLON || (BABYLON = {}));
  59797. //# sourceMappingURL=babylon.mirrorTexture.js.map
  59798. "use strict";
  59799. var BABYLON;
  59800. (function (BABYLON) {
  59801. /**
  59802. * Creates a refraction texture used by refraction channel of the standard material.
  59803. * @param name the texture name
  59804. * @param size size of the underlying texture
  59805. * @param scene root scene
  59806. */
  59807. var RefractionTexture = /** @class */ (function (_super) {
  59808. __extends(RefractionTexture, _super);
  59809. function RefractionTexture(name, size, scene, generateMipMaps) {
  59810. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  59811. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  59812. _this.depth = 2.0;
  59813. _this.onBeforeRenderObservable.add(function () {
  59814. scene.clipPlane = _this.refractionPlane;
  59815. });
  59816. _this.onAfterRenderObservable.add(function () {
  59817. delete scene.clipPlane;
  59818. });
  59819. return _this;
  59820. }
  59821. RefractionTexture.prototype.clone = function () {
  59822. var scene = this.getScene();
  59823. if (!scene) {
  59824. return this;
  59825. }
  59826. var textureSize = this.getSize();
  59827. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  59828. // Base texture
  59829. newTexture.hasAlpha = this.hasAlpha;
  59830. newTexture.level = this.level;
  59831. // Refraction Texture
  59832. newTexture.refractionPlane = this.refractionPlane.clone();
  59833. if (this.renderList) {
  59834. newTexture.renderList = this.renderList.slice(0);
  59835. }
  59836. newTexture.depth = this.depth;
  59837. return newTexture;
  59838. };
  59839. RefractionTexture.prototype.serialize = function () {
  59840. if (!this.name) {
  59841. return null;
  59842. }
  59843. var serializationObject = _super.prototype.serialize.call(this);
  59844. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  59845. serializationObject.depth = this.depth;
  59846. return serializationObject;
  59847. };
  59848. return RefractionTexture;
  59849. }(BABYLON.RenderTargetTexture));
  59850. BABYLON.RefractionTexture = RefractionTexture;
  59851. })(BABYLON || (BABYLON = {}));
  59852. //# sourceMappingURL=babylon.refractionTexture.js.map
  59853. "use strict";
  59854. var BABYLON;
  59855. (function (BABYLON) {
  59856. var DynamicTexture = /** @class */ (function (_super) {
  59857. __extends(DynamicTexture, _super);
  59858. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  59859. if (scene === void 0) { scene = null; }
  59860. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59861. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  59862. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  59863. _this.name = name;
  59864. _this._engine = _this.getScene().getEngine();
  59865. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59866. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  59867. _this._generateMipMaps = generateMipMaps;
  59868. if (options.getContext) {
  59869. _this._canvas = options;
  59870. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  59871. }
  59872. else {
  59873. _this._canvas = document.createElement("canvas");
  59874. if (options.width) {
  59875. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  59876. }
  59877. else {
  59878. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  59879. }
  59880. }
  59881. var textureSize = _this.getSize();
  59882. _this._canvas.width = textureSize.width;
  59883. _this._canvas.height = textureSize.height;
  59884. _this._context = _this._canvas.getContext("2d");
  59885. return _this;
  59886. }
  59887. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  59888. get: function () {
  59889. return true;
  59890. },
  59891. enumerable: true,
  59892. configurable: true
  59893. });
  59894. DynamicTexture.prototype._recreate = function (textureSize) {
  59895. this._canvas.width = textureSize.width;
  59896. this._canvas.height = textureSize.height;
  59897. this.releaseInternalTexture();
  59898. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  59899. };
  59900. DynamicTexture.prototype.scale = function (ratio) {
  59901. var textureSize = this.getSize();
  59902. textureSize.width *= ratio;
  59903. textureSize.height *= ratio;
  59904. this._recreate(textureSize);
  59905. };
  59906. DynamicTexture.prototype.scaleTo = function (width, height) {
  59907. var textureSize = this.getSize();
  59908. textureSize.width = width;
  59909. textureSize.height = height;
  59910. this._recreate(textureSize);
  59911. };
  59912. DynamicTexture.prototype.getContext = function () {
  59913. return this._context;
  59914. };
  59915. DynamicTexture.prototype.clear = function () {
  59916. var size = this.getSize();
  59917. this._context.fillRect(0, 0, size.width, size.height);
  59918. };
  59919. DynamicTexture.prototype.update = function (invertY) {
  59920. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  59921. };
  59922. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  59923. if (update === void 0) { update = true; }
  59924. var size = this.getSize();
  59925. if (clearColor) {
  59926. this._context.fillStyle = clearColor;
  59927. this._context.fillRect(0, 0, size.width, size.height);
  59928. }
  59929. this._context.font = font;
  59930. if (x === null || x === undefined) {
  59931. var textSize = this._context.measureText(text);
  59932. x = (size.width - textSize.width) / 2;
  59933. }
  59934. if (y === null || y === undefined) {
  59935. var fontSize = parseInt((font.replace(/\D/g, '')));
  59936. ;
  59937. y = (size.height / 2) + (fontSize / 3.65);
  59938. }
  59939. this._context.fillStyle = color;
  59940. this._context.fillText(text, x, y);
  59941. if (update) {
  59942. this.update(invertY);
  59943. }
  59944. };
  59945. DynamicTexture.prototype.clone = function () {
  59946. var scene = this.getScene();
  59947. if (!scene) {
  59948. return this;
  59949. }
  59950. var textureSize = this.getSize();
  59951. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  59952. // Base texture
  59953. newTexture.hasAlpha = this.hasAlpha;
  59954. newTexture.level = this.level;
  59955. // Dynamic Texture
  59956. newTexture.wrapU = this.wrapU;
  59957. newTexture.wrapV = this.wrapV;
  59958. return newTexture;
  59959. };
  59960. DynamicTexture.prototype._rebuild = function () {
  59961. this.update();
  59962. };
  59963. return DynamicTexture;
  59964. }(BABYLON.Texture));
  59965. BABYLON.DynamicTexture = DynamicTexture;
  59966. })(BABYLON || (BABYLON = {}));
  59967. //# sourceMappingURL=babylon.dynamicTexture.js.map
  59968. "use strict";
  59969. var BABYLON;
  59970. (function (BABYLON) {
  59971. var VideoTexture = /** @class */ (function (_super) {
  59972. __extends(VideoTexture, _super);
  59973. /**
  59974. * Creates a video texture.
  59975. * Sample : https://doc.babylonjs.com/how_to/video_texture
  59976. * @param {string | null} name optional name, will detect from video source, if not defined
  59977. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  59978. * @param {BABYLON.Scene} scene is obviously the current scene.
  59979. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  59980. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  59981. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  59982. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  59983. */
  59984. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  59985. if (generateMipMaps === void 0) { generateMipMaps = false; }
  59986. if (invertY === void 0) { invertY = false; }
  59987. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  59988. if (settings === void 0) { settings = {
  59989. autoPlay: true,
  59990. loop: true,
  59991. autoUpdateTexture: true,
  59992. }; }
  59993. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  59994. _this._createInternalTexture = function () {
  59995. if (_this._texture != null) {
  59996. return;
  59997. }
  59998. if (!_this._engine.needPOTTextures ||
  59999. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  60000. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  60001. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  60002. }
  60003. else {
  60004. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60005. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60006. _this._generateMipMaps = false;
  60007. }
  60008. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  60009. _this._texture.isReady = true;
  60010. _this._updateInternalTexture();
  60011. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  60012. _this.onLoadObservable.notifyObservers(_this);
  60013. }
  60014. };
  60015. _this.reset = function () {
  60016. if (_this._texture == null) {
  60017. return;
  60018. }
  60019. _this._texture.dispose();
  60020. _this._texture = null;
  60021. };
  60022. _this._updateInternalTexture = function (e) {
  60023. if (_this._texture == null || !_this._texture.isReady) {
  60024. return;
  60025. }
  60026. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  60027. return;
  60028. }
  60029. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  60030. };
  60031. _this._engine = _this.getScene().getEngine();
  60032. _this._generateMipMaps = generateMipMaps;
  60033. _this._samplingMode = samplingMode;
  60034. _this.autoUpdateTexture = settings.autoUpdateTexture;
  60035. _this.name = name || _this._getName(src);
  60036. _this.video = _this._getVideo(src);
  60037. if (settings.autoPlay !== undefined) {
  60038. _this.video.autoplay = settings.autoPlay;
  60039. }
  60040. if (settings.loop !== undefined) {
  60041. _this.video.loop = settings.loop;
  60042. }
  60043. _this.video.addEventListener("canplay", _this._createInternalTexture);
  60044. _this.video.addEventListener("paused", _this._updateInternalTexture);
  60045. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  60046. _this.video.addEventListener("emptied", _this.reset);
  60047. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  60048. _this._createInternalTexture();
  60049. }
  60050. return _this;
  60051. }
  60052. VideoTexture.prototype._getName = function (src) {
  60053. if (src instanceof HTMLVideoElement) {
  60054. return src.currentSrc;
  60055. }
  60056. if (typeof src === "object") {
  60057. return src.toString();
  60058. }
  60059. return src;
  60060. };
  60061. ;
  60062. VideoTexture.prototype._getVideo = function (src) {
  60063. if (src instanceof HTMLVideoElement) {
  60064. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  60065. return src;
  60066. }
  60067. var video = document.createElement("video");
  60068. if (typeof src === "string") {
  60069. BABYLON.Tools.SetCorsBehavior(src, video);
  60070. video.src = src;
  60071. }
  60072. else {
  60073. BABYLON.Tools.SetCorsBehavior(src[0], video);
  60074. src.forEach(function (url) {
  60075. var source = document.createElement("source");
  60076. source.src = url;
  60077. video.appendChild(source);
  60078. });
  60079. }
  60080. return video;
  60081. };
  60082. ;
  60083. /**
  60084. * Internal method to initiate `update`.
  60085. */
  60086. VideoTexture.prototype._rebuild = function () {
  60087. this.update();
  60088. };
  60089. /**
  60090. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  60091. */
  60092. VideoTexture.prototype.update = function () {
  60093. if (!this.autoUpdateTexture) {
  60094. // Expecting user to call `updateTexture` manually
  60095. return;
  60096. }
  60097. this.updateTexture(true);
  60098. };
  60099. /**
  60100. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  60101. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  60102. */
  60103. VideoTexture.prototype.updateTexture = function (isVisible) {
  60104. if (!isVisible) {
  60105. return;
  60106. }
  60107. if (this.video.paused) {
  60108. return;
  60109. }
  60110. this._updateInternalTexture();
  60111. };
  60112. /**
  60113. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  60114. * @param url New url.
  60115. */
  60116. VideoTexture.prototype.updateURL = function (url) {
  60117. this.video.src = url;
  60118. };
  60119. VideoTexture.prototype.dispose = function () {
  60120. _super.prototype.dispose.call(this);
  60121. this.video.removeEventListener("canplay", this._createInternalTexture);
  60122. this.video.removeEventListener("paused", this._updateInternalTexture);
  60123. this.video.removeEventListener("seeked", this._updateInternalTexture);
  60124. this.video.removeEventListener("emptied", this.reset);
  60125. this.video.pause();
  60126. };
  60127. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  60128. var video = document.createElement("video");
  60129. var constraintsDeviceId;
  60130. if (constraints && constraints.deviceId) {
  60131. constraintsDeviceId = {
  60132. exact: constraints.deviceId,
  60133. };
  60134. }
  60135. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  60136. if (navigator.mediaDevices) {
  60137. navigator.mediaDevices.getUserMedia({ video: constraints })
  60138. .then(function (stream) {
  60139. if (video.mozSrcObject !== undefined) {
  60140. // hack for Firefox < 19
  60141. video.mozSrcObject = stream;
  60142. }
  60143. else {
  60144. video.srcObject = stream;
  60145. }
  60146. var onPlaying = function () {
  60147. if (onReady) {
  60148. onReady(new VideoTexture("video", video, scene, true, true));
  60149. }
  60150. video.removeEventListener("playing", onPlaying);
  60151. };
  60152. video.addEventListener("playing", onPlaying);
  60153. video.play();
  60154. })
  60155. .catch(function (err) {
  60156. BABYLON.Tools.Error(err.name);
  60157. });
  60158. }
  60159. else {
  60160. navigator.getUserMedia =
  60161. navigator.getUserMedia ||
  60162. navigator.webkitGetUserMedia ||
  60163. navigator.mozGetUserMedia ||
  60164. navigator.msGetUserMedia;
  60165. if (navigator.getUserMedia) {
  60166. navigator.getUserMedia({
  60167. video: {
  60168. deviceId: constraintsDeviceId,
  60169. width: {
  60170. min: (constraints && constraints.minWidth) || 256,
  60171. max: (constraints && constraints.maxWidth) || 640,
  60172. },
  60173. height: {
  60174. min: (constraints && constraints.minHeight) || 256,
  60175. max: (constraints && constraints.maxHeight) || 480,
  60176. },
  60177. },
  60178. }, function (stream) {
  60179. if (video.mozSrcObject !== undefined) {
  60180. // hack for Firefox < 19
  60181. video.mozSrcObject = stream;
  60182. }
  60183. else {
  60184. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  60185. }
  60186. video.play();
  60187. if (onReady) {
  60188. onReady(new VideoTexture("video", video, scene, true, true));
  60189. }
  60190. }, function (e) {
  60191. BABYLON.Tools.Error(e.name);
  60192. });
  60193. }
  60194. }
  60195. };
  60196. return VideoTexture;
  60197. }(BABYLON.Texture));
  60198. BABYLON.VideoTexture = VideoTexture;
  60199. })(BABYLON || (BABYLON = {}));
  60200. //# sourceMappingURL=babylon.videoTexture.js.map
  60201. "use strict";
  60202. var BABYLON;
  60203. (function (BABYLON) {
  60204. var RawTexture = /** @class */ (function (_super) {
  60205. __extends(RawTexture, _super);
  60206. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  60207. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60208. if (invertY === void 0) { invertY = false; }
  60209. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60210. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60211. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  60212. _this.format = format;
  60213. _this._engine = scene.getEngine();
  60214. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  60215. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60216. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  60217. return _this;
  60218. }
  60219. RawTexture.prototype.update = function (data) {
  60220. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  60221. };
  60222. // Statics
  60223. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  60224. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60225. if (invertY === void 0) { invertY = false; }
  60226. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60227. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  60228. };
  60229. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  60230. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60231. if (invertY === void 0) { invertY = false; }
  60232. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60233. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  60234. };
  60235. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  60236. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60237. if (invertY === void 0) { invertY = false; }
  60238. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60239. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  60240. };
  60241. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  60242. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60243. if (invertY === void 0) { invertY = false; }
  60244. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60245. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60246. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  60247. };
  60248. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  60249. if (generateMipMaps === void 0) { generateMipMaps = true; }
  60250. if (invertY === void 0) { invertY = false; }
  60251. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  60252. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60253. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  60254. };
  60255. return RawTexture;
  60256. }(BABYLON.Texture));
  60257. BABYLON.RawTexture = RawTexture;
  60258. })(BABYLON || (BABYLON = {}));
  60259. //# sourceMappingURL=babylon.rawTexture.js.map
  60260. "use strict";
  60261. var BABYLON;
  60262. (function (BABYLON) {
  60263. /**
  60264. * PostProcess can be used to apply a shader to a texture after it has been rendered
  60265. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  60266. */
  60267. var PostProcess = /** @class */ (function () {
  60268. /**
  60269. * Creates a new instance of @see PostProcess
  60270. * @param name The name of the PostProcess.
  60271. * @param fragmentUrl The url of the fragment shader to be used.
  60272. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  60273. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  60274. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  60275. * @param camera The camera to apply the render pass to.
  60276. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  60277. * @param engine The engine which the post process will be applied. (default: current engine)
  60278. * @param reusable If the post process can be reused on the same frame. (default: false)
  60279. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  60280. * @param textureType Type of textures used when performing the post process. (default: 0)
  60281. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  60282. * @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
  60283. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  60284. */
  60285. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  60286. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  60287. if (defines === void 0) { defines = null; }
  60288. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60289. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  60290. if (blockCompilation === void 0) { blockCompilation = false; }
  60291. this.name = name;
  60292. /**
  60293. * Width of the texture to apply the post process on
  60294. */
  60295. this.width = -1;
  60296. /**
  60297. * Height of the texture to apply the post process on
  60298. */
  60299. this.height = -1;
  60300. /**
  60301. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  60302. */
  60303. this._outputTexture = null;
  60304. /**
  60305. * If the buffer needs to be cleared before applying the post process. (default: true)
  60306. * Should be set to false if shader will overwrite all previous pixels.
  60307. */
  60308. this.autoClear = true;
  60309. /**
  60310. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  60311. */
  60312. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  60313. /**
  60314. * Animations to be used for the post processing
  60315. */
  60316. this.animations = new Array();
  60317. /**
  60318. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  60319. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  60320. */
  60321. this.enablePixelPerfectMode = false;
  60322. /**
  60323. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  60324. */
  60325. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  60326. /**
  60327. * Force textures to be a power of two (default: false)
  60328. */
  60329. this.alwaysForcePOT = false;
  60330. /**
  60331. * Number of sample textures (default: 1)
  60332. */
  60333. this.samples = 1;
  60334. /**
  60335. * Modify the scale of the post process to be the same as the viewport (default: false)
  60336. */
  60337. this.adaptScaleToCurrentViewport = false;
  60338. this._reusable = false;
  60339. /**
  60340. * Smart array of input and output textures for the post process.
  60341. */
  60342. this._textures = new BABYLON.SmartArray(2);
  60343. /**
  60344. * The index in _textures that corresponds to the output texture.
  60345. */
  60346. this._currentRenderTextureInd = 0;
  60347. this._scaleRatio = new BABYLON.Vector2(1, 1);
  60348. this._texelSize = BABYLON.Vector2.Zero();
  60349. // Events
  60350. /**
  60351. * An event triggered when the postprocess is activated.
  60352. * @type {BABYLON.Observable}
  60353. */
  60354. this.onActivateObservable = new BABYLON.Observable();
  60355. /**
  60356. * An event triggered when the postprocess changes its size.
  60357. * @type {BABYLON.Observable}
  60358. */
  60359. this.onSizeChangedObservable = new BABYLON.Observable();
  60360. /**
  60361. * An event triggered when the postprocess applies its effect.
  60362. * @type {BABYLON.Observable}
  60363. */
  60364. this.onApplyObservable = new BABYLON.Observable();
  60365. /**
  60366. * An event triggered before rendering the postprocess
  60367. * @type {BABYLON.Observable}
  60368. */
  60369. this.onBeforeRenderObservable = new BABYLON.Observable();
  60370. /**
  60371. * An event triggered after rendering the postprocess
  60372. * @type {BABYLON.Observable}
  60373. */
  60374. this.onAfterRenderObservable = new BABYLON.Observable();
  60375. if (camera != null) {
  60376. this._camera = camera;
  60377. this._scene = camera.getScene();
  60378. camera.attachPostProcess(this);
  60379. this._engine = this._scene.getEngine();
  60380. this._scene.postProcesses.push(this);
  60381. }
  60382. else if (engine) {
  60383. this._engine = engine;
  60384. this._engine.postProcesses.push(this);
  60385. }
  60386. this._options = options;
  60387. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  60388. this._reusable = reusable || false;
  60389. this._textureType = textureType;
  60390. this._samplers = samplers || [];
  60391. this._samplers.push("textureSampler");
  60392. this._fragmentUrl = fragmentUrl;
  60393. this._vertexUrl = vertexUrl;
  60394. this._parameters = parameters || [];
  60395. this._parameters.push("scale");
  60396. this._indexParameters = indexParameters;
  60397. if (!blockCompilation) {
  60398. this.updateEffect(defines);
  60399. }
  60400. }
  60401. Object.defineProperty(PostProcess.prototype, "onActivate", {
  60402. /**
  60403. * A function that is added to the onActivateObservable
  60404. */
  60405. set: function (callback) {
  60406. if (this._onActivateObserver) {
  60407. this.onActivateObservable.remove(this._onActivateObserver);
  60408. }
  60409. if (callback) {
  60410. this._onActivateObserver = this.onActivateObservable.add(callback);
  60411. }
  60412. },
  60413. enumerable: true,
  60414. configurable: true
  60415. });
  60416. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  60417. /**
  60418. * A function that is added to the onSizeChangedObservable
  60419. */
  60420. set: function (callback) {
  60421. if (this._onSizeChangedObserver) {
  60422. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  60423. }
  60424. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  60425. },
  60426. enumerable: true,
  60427. configurable: true
  60428. });
  60429. Object.defineProperty(PostProcess.prototype, "onApply", {
  60430. /**
  60431. * A function that is added to the onApplyObservable
  60432. */
  60433. set: function (callback) {
  60434. if (this._onApplyObserver) {
  60435. this.onApplyObservable.remove(this._onApplyObserver);
  60436. }
  60437. this._onApplyObserver = this.onApplyObservable.add(callback);
  60438. },
  60439. enumerable: true,
  60440. configurable: true
  60441. });
  60442. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  60443. /**
  60444. * A function that is added to the onBeforeRenderObservable
  60445. */
  60446. set: function (callback) {
  60447. if (this._onBeforeRenderObserver) {
  60448. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  60449. }
  60450. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  60451. },
  60452. enumerable: true,
  60453. configurable: true
  60454. });
  60455. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  60456. /**
  60457. * A function that is added to the onAfterRenderObservable
  60458. */
  60459. set: function (callback) {
  60460. if (this._onAfterRenderObserver) {
  60461. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  60462. }
  60463. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  60464. },
  60465. enumerable: true,
  60466. configurable: true
  60467. });
  60468. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  60469. /**
  60470. * 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
  60471. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  60472. */
  60473. get: function () {
  60474. return this._textures.data[this._currentRenderTextureInd];
  60475. },
  60476. set: function (value) {
  60477. this._forcedOutputTexture = value;
  60478. },
  60479. enumerable: true,
  60480. configurable: true
  60481. });
  60482. /**
  60483. * Gets the camera which post process is applied to.
  60484. * @returns The camera the post process is applied to.
  60485. */
  60486. PostProcess.prototype.getCamera = function () {
  60487. return this._camera;
  60488. };
  60489. Object.defineProperty(PostProcess.prototype, "texelSize", {
  60490. /**
  60491. * Gets the texel size of the postprocess.
  60492. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  60493. */
  60494. get: function () {
  60495. if (this._shareOutputWithPostProcess) {
  60496. return this._shareOutputWithPostProcess.texelSize;
  60497. }
  60498. if (this._forcedOutputTexture) {
  60499. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  60500. }
  60501. return this._texelSize;
  60502. },
  60503. enumerable: true,
  60504. configurable: true
  60505. });
  60506. /**
  60507. * Gets the engine which this post process belongs to.
  60508. * @returns The engine the post process was enabled with.
  60509. */
  60510. PostProcess.prototype.getEngine = function () {
  60511. return this._engine;
  60512. };
  60513. /**
  60514. * The effect that is created when initializing the post process.
  60515. * @returns The created effect corrisponding the the postprocess.
  60516. */
  60517. PostProcess.prototype.getEffect = function () {
  60518. return this._effect;
  60519. };
  60520. /**
  60521. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  60522. * @param postProcess The post process to share the output with.
  60523. * @returns This post process.
  60524. */
  60525. PostProcess.prototype.shareOutputWith = function (postProcess) {
  60526. this._disposeTextures();
  60527. this._shareOutputWithPostProcess = postProcess;
  60528. return this;
  60529. };
  60530. /**
  60531. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  60532. * This should be called if the post process that shares output with this post process is disabled/disposed.
  60533. */
  60534. PostProcess.prototype.useOwnOutput = function () {
  60535. if (this._textures.length == 0) {
  60536. this._textures = new BABYLON.SmartArray(2);
  60537. }
  60538. this._shareOutputWithPostProcess = null;
  60539. };
  60540. /**
  60541. * Updates the effect with the current post process compile time values and recompiles the shader.
  60542. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  60543. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  60544. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  60545. * @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
  60546. * @param onCompiled Called when the shader has been compiled.
  60547. * @param onError Called if there is an error when compiling a shader.
  60548. */
  60549. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  60550. if (defines === void 0) { defines = null; }
  60551. if (uniforms === void 0) { uniforms = null; }
  60552. if (samplers === void 0) { samplers = null; }
  60553. 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);
  60554. };
  60555. /**
  60556. * The post process is reusable if it can be used multiple times within one frame.
  60557. * @returns If the post process is reusable
  60558. */
  60559. PostProcess.prototype.isReusable = function () {
  60560. return this._reusable;
  60561. };
  60562. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  60563. PostProcess.prototype.markTextureDirty = function () {
  60564. this.width = -1;
  60565. };
  60566. /**
  60567. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  60568. * 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.
  60569. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  60570. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  60571. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  60572. * @returns The target texture that was bound to be written to.
  60573. */
  60574. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  60575. var _this = this;
  60576. if (sourceTexture === void 0) { sourceTexture = null; }
  60577. camera = camera || this._camera;
  60578. var scene = camera.getScene();
  60579. var engine = scene.getEngine();
  60580. var maxSize = engine.getCaps().maxTextureSize;
  60581. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  60582. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  60583. // 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
  60584. var webVRCamera = camera.parent;
  60585. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  60586. requiredWidth /= 2;
  60587. }
  60588. var desiredWidth = (this._options.width || requiredWidth);
  60589. var desiredHeight = this._options.height || requiredHeight;
  60590. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  60591. if (this.adaptScaleToCurrentViewport) {
  60592. var currentViewport = engine.currentViewport;
  60593. if (currentViewport) {
  60594. desiredWidth *= currentViewport.width;
  60595. desiredHeight *= currentViewport.height;
  60596. }
  60597. }
  60598. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  60599. if (!this._options.width) {
  60600. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  60601. }
  60602. if (!this._options.height) {
  60603. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  60604. }
  60605. }
  60606. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  60607. if (this._textures.length > 0) {
  60608. for (var i = 0; i < this._textures.length; i++) {
  60609. this._engine._releaseTexture(this._textures.data[i]);
  60610. }
  60611. this._textures.reset();
  60612. }
  60613. this.width = desiredWidth;
  60614. this.height = desiredHeight;
  60615. var textureSize = { width: this.width, height: this.height };
  60616. var textureOptions = {
  60617. generateMipMaps: false,
  60618. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  60619. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  60620. samplingMode: this.renderTargetSamplingMode,
  60621. type: this._textureType
  60622. };
  60623. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  60624. if (this._reusable) {
  60625. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  60626. }
  60627. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  60628. this.onSizeChangedObservable.notifyObservers(this);
  60629. }
  60630. this._textures.forEach(function (texture) {
  60631. if (texture.samples !== _this.samples) {
  60632. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  60633. }
  60634. });
  60635. }
  60636. var target;
  60637. if (this._shareOutputWithPostProcess) {
  60638. target = this._shareOutputWithPostProcess.inputTexture;
  60639. }
  60640. else if (this._forcedOutputTexture) {
  60641. target = this._forcedOutputTexture;
  60642. this.width = this._forcedOutputTexture.width;
  60643. this.height = this._forcedOutputTexture.height;
  60644. }
  60645. else {
  60646. target = this.inputTexture;
  60647. }
  60648. // Bind the input of this post process to be used as the output of the previous post process.
  60649. if (this.enablePixelPerfectMode) {
  60650. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  60651. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  60652. }
  60653. else {
  60654. this._scaleRatio.copyFromFloats(1, 1);
  60655. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  60656. }
  60657. this.onActivateObservable.notifyObservers(camera);
  60658. // Clear
  60659. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  60660. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  60661. }
  60662. if (this._reusable) {
  60663. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  60664. }
  60665. return target;
  60666. };
  60667. Object.defineProperty(PostProcess.prototype, "isSupported", {
  60668. /**
  60669. * If the post process is supported.
  60670. */
  60671. get: function () {
  60672. return this._effect.isSupported;
  60673. },
  60674. enumerable: true,
  60675. configurable: true
  60676. });
  60677. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  60678. /**
  60679. * The aspect ratio of the output texture.
  60680. */
  60681. get: function () {
  60682. if (this._shareOutputWithPostProcess) {
  60683. return this._shareOutputWithPostProcess.aspectRatio;
  60684. }
  60685. if (this._forcedOutputTexture) {
  60686. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  60687. }
  60688. return this.width / this.height;
  60689. },
  60690. enumerable: true,
  60691. configurable: true
  60692. });
  60693. /**
  60694. * Get a value indicating if the post-process is ready to be used
  60695. * @returns true if the post-process is ready (shader is compiled)
  60696. */
  60697. PostProcess.prototype.isReady = function () {
  60698. return this._effect && this._effect.isReady();
  60699. };
  60700. /**
  60701. * Binds all textures and uniforms to the shader, this will be run on every pass.
  60702. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  60703. */
  60704. PostProcess.prototype.apply = function () {
  60705. // Check
  60706. if (!this._effect || !this._effect.isReady())
  60707. return null;
  60708. // States
  60709. this._engine.enableEffect(this._effect);
  60710. this._engine.setState(false);
  60711. this._engine.setDepthBuffer(false);
  60712. this._engine.setDepthWrite(false);
  60713. // Alpha
  60714. this._engine.setAlphaMode(this.alphaMode);
  60715. if (this.alphaConstants) {
  60716. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  60717. }
  60718. // Bind the output texture of the preivous post process as the input to this post process.
  60719. var source;
  60720. if (this._shareOutputWithPostProcess) {
  60721. source = this._shareOutputWithPostProcess.inputTexture;
  60722. }
  60723. else if (this._forcedOutputTexture) {
  60724. source = this._forcedOutputTexture;
  60725. }
  60726. else {
  60727. source = this.inputTexture;
  60728. }
  60729. this._effect._bindTexture("textureSampler", source);
  60730. // Parameters
  60731. this._effect.setVector2("scale", this._scaleRatio);
  60732. this.onApplyObservable.notifyObservers(this._effect);
  60733. return this._effect;
  60734. };
  60735. PostProcess.prototype._disposeTextures = function () {
  60736. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  60737. return;
  60738. }
  60739. if (this._textures.length > 0) {
  60740. for (var i = 0; i < this._textures.length; i++) {
  60741. this._engine._releaseTexture(this._textures.data[i]);
  60742. }
  60743. }
  60744. this._textures.dispose();
  60745. };
  60746. /**
  60747. * Disposes the post process.
  60748. * @param camera The camera to dispose the post process on.
  60749. */
  60750. PostProcess.prototype.dispose = function (camera) {
  60751. camera = camera || this._camera;
  60752. this._disposeTextures();
  60753. if (this._scene) {
  60754. var index_1 = this._scene.postProcesses.indexOf(this);
  60755. if (index_1 !== -1) {
  60756. this._scene.postProcesses.splice(index_1, 1);
  60757. }
  60758. }
  60759. else {
  60760. var index_2 = this._engine.postProcesses.indexOf(this);
  60761. if (index_2 !== -1) {
  60762. this._engine.postProcesses.splice(index_2, 1);
  60763. }
  60764. }
  60765. if (!camera) {
  60766. return;
  60767. }
  60768. camera.detachPostProcess(this);
  60769. var index = camera._postProcesses.indexOf(this);
  60770. if (index === 0 && camera._postProcesses.length > 0) {
  60771. var firstPostProcess = this._camera._getFirstPostProcess();
  60772. if (firstPostProcess) {
  60773. firstPostProcess.markTextureDirty();
  60774. }
  60775. }
  60776. this.onActivateObservable.clear();
  60777. this.onAfterRenderObservable.clear();
  60778. this.onApplyObservable.clear();
  60779. this.onBeforeRenderObservable.clear();
  60780. this.onSizeChangedObservable.clear();
  60781. };
  60782. return PostProcess;
  60783. }());
  60784. BABYLON.PostProcess = PostProcess;
  60785. })(BABYLON || (BABYLON = {}));
  60786. //# sourceMappingURL=babylon.postProcess.js.map
  60787. "use strict";
  60788. var BABYLON;
  60789. (function (BABYLON) {
  60790. var PassPostProcess = /** @class */ (function (_super) {
  60791. __extends(PassPostProcess, _super);
  60792. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  60793. if (camera === void 0) { camera = null; }
  60794. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  60795. if (blockCompilation === void 0) { blockCompilation = false; }
  60796. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  60797. }
  60798. return PassPostProcess;
  60799. }(BABYLON.PostProcess));
  60800. BABYLON.PassPostProcess = PassPostProcess;
  60801. })(BABYLON || (BABYLON = {}));
  60802. //# sourceMappingURL=babylon.passPostProcess.js.map
  60803. "use strict";
  60804. var __assign = (this && this.__assign) || Object.assign || function(t) {
  60805. for (var s, i = 1, n = arguments.length; i < n; i++) {
  60806. s = arguments[i];
  60807. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  60808. t[p] = s[p];
  60809. }
  60810. return t;
  60811. };
  60812. var BABYLON;
  60813. (function (BABYLON) {
  60814. /**
  60815. * Default implementation of @see IShadowGenerator.
  60816. * This is the main object responsible of generating shadows in the framework.
  60817. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  60818. */
  60819. var ShadowGenerator = /** @class */ (function () {
  60820. /**
  60821. * Creates a ShadowGenerator object.
  60822. * A ShadowGenerator is the required tool to use the shadows.
  60823. * Each light casting shadows needs to use its own ShadowGenerator.
  60824. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  60825. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  60826. * @param light The light object generating the shadows.
  60827. * @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.
  60828. */
  60829. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  60830. this._bias = 0.00005;
  60831. this._normalBias = 0;
  60832. this._blurBoxOffset = 1;
  60833. this._blurScale = 2;
  60834. this._blurKernel = 1;
  60835. this._useKernelBlur = false;
  60836. this._filter = ShadowGenerator.FILTER_NONE;
  60837. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  60838. this._contactHardeningLightSizeUVRatio = 0.1;
  60839. this._darkness = 0;
  60840. this._transparencyShadow = false;
  60841. /**
  60842. * Controls the extent to which the shadows fade out at the edge of the frustum
  60843. * Used only by directionals and spots
  60844. */
  60845. this.frustumEdgeFalloff = 0;
  60846. /**
  60847. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  60848. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  60849. * It might on the other hand introduce peter panning.
  60850. */
  60851. this.forceBackFacesOnly = false;
  60852. this._lightDirection = BABYLON.Vector3.Zero();
  60853. this._viewMatrix = BABYLON.Matrix.Zero();
  60854. this._projectionMatrix = BABYLON.Matrix.Zero();
  60855. this._transformMatrix = BABYLON.Matrix.Zero();
  60856. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  60857. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  60858. this._currentFaceIndex = 0;
  60859. this._currentFaceIndexCache = 0;
  60860. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  60861. this._mapSize = mapSize;
  60862. this._light = light;
  60863. this._scene = light.getScene();
  60864. light._shadowGenerator = this;
  60865. // Texture type fallback from float to int if not supported.
  60866. var caps = this._scene.getEngine().getCaps();
  60867. if (!useFullFloatFirst) {
  60868. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  60869. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60870. }
  60871. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  60872. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  60873. }
  60874. else {
  60875. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  60876. }
  60877. }
  60878. else {
  60879. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  60880. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  60881. }
  60882. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  60883. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  60884. }
  60885. else {
  60886. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  60887. }
  60888. }
  60889. this._initializeGenerator();
  60890. this._applyFilterValues();
  60891. }
  60892. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  60893. /**
  60894. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  60895. */
  60896. get: function () {
  60897. return this._bias;
  60898. },
  60899. /**
  60900. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  60901. */
  60902. set: function (bias) {
  60903. this._bias = bias;
  60904. },
  60905. enumerable: true,
  60906. configurable: true
  60907. });
  60908. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  60909. /**
  60910. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  60911. */
  60912. get: function () {
  60913. return this._normalBias;
  60914. },
  60915. /**
  60916. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  60917. */
  60918. set: function (normalBias) {
  60919. this._normalBias = normalBias;
  60920. },
  60921. enumerable: true,
  60922. configurable: true
  60923. });
  60924. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  60925. /**
  60926. * Gets the blur box offset: offset applied during the blur pass.
  60927. * Only usefull if useKernelBlur = false
  60928. */
  60929. get: function () {
  60930. return this._blurBoxOffset;
  60931. },
  60932. /**
  60933. * Sets the blur box offset: offset applied during the blur pass.
  60934. * Only usefull if useKernelBlur = false
  60935. */
  60936. set: function (value) {
  60937. if (this._blurBoxOffset === value) {
  60938. return;
  60939. }
  60940. this._blurBoxOffset = value;
  60941. this._disposeBlurPostProcesses();
  60942. },
  60943. enumerable: true,
  60944. configurable: true
  60945. });
  60946. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  60947. /**
  60948. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  60949. * 2 means half of the size.
  60950. */
  60951. get: function () {
  60952. return this._blurScale;
  60953. },
  60954. /**
  60955. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  60956. * 2 means half of the size.
  60957. */
  60958. set: function (value) {
  60959. if (this._blurScale === value) {
  60960. return;
  60961. }
  60962. this._blurScale = value;
  60963. this._disposeBlurPostProcesses();
  60964. },
  60965. enumerable: true,
  60966. configurable: true
  60967. });
  60968. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  60969. /**
  60970. * Gets the blur kernel: kernel size of the blur pass.
  60971. * Only usefull if useKernelBlur = true
  60972. */
  60973. get: function () {
  60974. return this._blurKernel;
  60975. },
  60976. /**
  60977. * Sets the blur kernel: kernel size of the blur pass.
  60978. * Only usefull if useKernelBlur = true
  60979. */
  60980. set: function (value) {
  60981. if (this._blurKernel === value) {
  60982. return;
  60983. }
  60984. this._blurKernel = value;
  60985. this._disposeBlurPostProcesses();
  60986. },
  60987. enumerable: true,
  60988. configurable: true
  60989. });
  60990. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  60991. /**
  60992. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  60993. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  60994. */
  60995. get: function () {
  60996. return this._useKernelBlur;
  60997. },
  60998. /**
  60999. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  61000. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  61001. */
  61002. set: function (value) {
  61003. if (this._useKernelBlur === value) {
  61004. return;
  61005. }
  61006. this._useKernelBlur = value;
  61007. this._disposeBlurPostProcesses();
  61008. },
  61009. enumerable: true,
  61010. configurable: true
  61011. });
  61012. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  61013. /**
  61014. * Gets the depth scale used in ESM mode.
  61015. */
  61016. get: function () {
  61017. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  61018. },
  61019. /**
  61020. * Sets the depth scale used in ESM mode.
  61021. * This can override the scale stored on the light.
  61022. */
  61023. set: function (value) {
  61024. this._depthScale = value;
  61025. },
  61026. enumerable: true,
  61027. configurable: true
  61028. });
  61029. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  61030. /**
  61031. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  61032. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  61033. */
  61034. get: function () {
  61035. return this._filter;
  61036. },
  61037. /**
  61038. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  61039. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  61040. */
  61041. set: function (value) {
  61042. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  61043. if (this._light.needCube()) {
  61044. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  61045. this.useExponentialShadowMap = true;
  61046. return;
  61047. }
  61048. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  61049. this.useCloseExponentialShadowMap = true;
  61050. return;
  61051. }
  61052. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  61053. this.usePoissonSampling = true;
  61054. return;
  61055. }
  61056. }
  61057. // Weblg1 fallback for PCF.
  61058. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  61059. if (this._scene.getEngine().webGLVersion === 1) {
  61060. this.usePoissonSampling = true;
  61061. return;
  61062. }
  61063. }
  61064. if (this._filter === value) {
  61065. return;
  61066. }
  61067. this._filter = value;
  61068. this._disposeBlurPostProcesses();
  61069. this._applyFilterValues();
  61070. this._light._markMeshesAsLightDirty();
  61071. },
  61072. enumerable: true,
  61073. configurable: true
  61074. });
  61075. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  61076. /**
  61077. * Gets if the current filter is set to Poisson Sampling.
  61078. */
  61079. get: function () {
  61080. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  61081. },
  61082. /**
  61083. * Sets the current filter to Poisson Sampling.
  61084. */
  61085. set: function (value) {
  61086. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  61087. return;
  61088. }
  61089. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  61090. },
  61091. enumerable: true,
  61092. configurable: true
  61093. });
  61094. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  61095. /**
  61096. * Gets if the current filter is set to VSM.
  61097. * DEPRECATED. Should use useExponentialShadowMap instead.
  61098. */
  61099. get: function () {
  61100. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  61101. return this.useExponentialShadowMap;
  61102. },
  61103. /**
  61104. * Sets the current filter is to VSM.
  61105. * DEPRECATED. Should use useExponentialShadowMap instead.
  61106. */
  61107. set: function (value) {
  61108. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  61109. this.useExponentialShadowMap = value;
  61110. },
  61111. enumerable: true,
  61112. configurable: true
  61113. });
  61114. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  61115. /**
  61116. * Gets if the current filter is set to blurred VSM.
  61117. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  61118. */
  61119. get: function () {
  61120. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  61121. return this.useBlurExponentialShadowMap;
  61122. },
  61123. /**
  61124. * Sets the current filter is to blurred VSM.
  61125. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  61126. */
  61127. set: function (value) {
  61128. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  61129. this.useBlurExponentialShadowMap = value;
  61130. },
  61131. enumerable: true,
  61132. configurable: true
  61133. });
  61134. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  61135. /**
  61136. * Gets if the current filter is set to ESM.
  61137. */
  61138. get: function () {
  61139. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  61140. },
  61141. /**
  61142. * Sets the current filter is to ESM.
  61143. */
  61144. set: function (value) {
  61145. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  61146. return;
  61147. }
  61148. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  61149. },
  61150. enumerable: true,
  61151. configurable: true
  61152. });
  61153. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  61154. /**
  61155. * Gets if the current filter is set to filtered ESM.
  61156. */
  61157. get: function () {
  61158. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  61159. },
  61160. /**
  61161. * Gets if the current filter is set to filtered ESM.
  61162. */
  61163. set: function (value) {
  61164. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  61165. return;
  61166. }
  61167. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  61168. },
  61169. enumerable: true,
  61170. configurable: true
  61171. });
  61172. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  61173. /**
  61174. * Gets if the current filter is set to "close ESM" (using the inverse of the
  61175. * exponential to prevent steep falloff artifacts).
  61176. */
  61177. get: function () {
  61178. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  61179. },
  61180. /**
  61181. * Sets the current filter to "close ESM" (using the inverse of the
  61182. * exponential to prevent steep falloff artifacts).
  61183. */
  61184. set: function (value) {
  61185. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  61186. return;
  61187. }
  61188. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  61189. },
  61190. enumerable: true,
  61191. configurable: true
  61192. });
  61193. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  61194. /**
  61195. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  61196. * exponential to prevent steep falloff artifacts).
  61197. */
  61198. get: function () {
  61199. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  61200. },
  61201. /**
  61202. * Sets the current filter to filtered "close ESM" (using the inverse of the
  61203. * exponential to prevent steep falloff artifacts).
  61204. */
  61205. set: function (value) {
  61206. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  61207. return;
  61208. }
  61209. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  61210. },
  61211. enumerable: true,
  61212. configurable: true
  61213. });
  61214. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  61215. /**
  61216. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  61217. */
  61218. get: function () {
  61219. return this.filter === ShadowGenerator.FILTER_PCF;
  61220. },
  61221. /**
  61222. * Sets the current filter to "PCF" (percentage closer filtering).
  61223. */
  61224. set: function (value) {
  61225. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  61226. return;
  61227. }
  61228. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  61229. },
  61230. enumerable: true,
  61231. configurable: true
  61232. });
  61233. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  61234. /**
  61235. * Gets the PCF or PCSS Quality.
  61236. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  61237. */
  61238. get: function () {
  61239. return this._filteringQuality;
  61240. },
  61241. /**
  61242. * Sets the PCF or PCSS Quality.
  61243. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  61244. */
  61245. set: function (filteringQuality) {
  61246. this._filteringQuality = filteringQuality;
  61247. },
  61248. enumerable: true,
  61249. configurable: true
  61250. });
  61251. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  61252. /**
  61253. * Gets if the current filter is set to "PCSS" (contact hardening).
  61254. */
  61255. get: function () {
  61256. return this.filter === ShadowGenerator.FILTER_PCSS;
  61257. },
  61258. /**
  61259. * Sets the current filter to "PCSS" (contact hardening).
  61260. */
  61261. set: function (value) {
  61262. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  61263. return;
  61264. }
  61265. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  61266. },
  61267. enumerable: true,
  61268. configurable: true
  61269. });
  61270. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  61271. /**
  61272. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  61273. * Using a ratio helps keeping shape stability independently of the map size.
  61274. *
  61275. * It does not account for the light projection as it was having too much
  61276. * instability during the light setup or during light position changes.
  61277. *
  61278. * Only valid if useContactHardeningShadow is true.
  61279. */
  61280. get: function () {
  61281. return this._contactHardeningLightSizeUVRatio;
  61282. },
  61283. /**
  61284. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  61285. * Using a ratio helps keeping shape stability independently of the map size.
  61286. *
  61287. * It does not account for the light projection as it was having too much
  61288. * instability during the light setup or during light position changes.
  61289. *
  61290. * Only valid if useContactHardeningShadow is true.
  61291. */
  61292. set: function (contactHardeningLightSizeUVRatio) {
  61293. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  61294. },
  61295. enumerable: true,
  61296. configurable: true
  61297. });
  61298. /**
  61299. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  61300. * 0 means strongest and 1 would means no shadow.
  61301. * @returns the darkness.
  61302. */
  61303. ShadowGenerator.prototype.getDarkness = function () {
  61304. return this._darkness;
  61305. };
  61306. /**
  61307. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  61308. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  61309. * @returns the shadow generator allowing fluent coding.
  61310. */
  61311. ShadowGenerator.prototype.setDarkness = function (darkness) {
  61312. if (darkness >= 1.0)
  61313. this._darkness = 1.0;
  61314. else if (darkness <= 0.0)
  61315. this._darkness = 0.0;
  61316. else
  61317. this._darkness = darkness;
  61318. return this;
  61319. };
  61320. /**
  61321. * Sets the ability to have transparent shadow (boolean).
  61322. * @param transparent True if transparent else False
  61323. * @returns the shadow generator allowing fluent coding
  61324. */
  61325. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  61326. this._transparencyShadow = transparent;
  61327. return this;
  61328. };
  61329. /**
  61330. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  61331. * @returns The render target texture if present otherwise, null
  61332. */
  61333. ShadowGenerator.prototype.getShadowMap = function () {
  61334. return this._shadowMap;
  61335. };
  61336. /**
  61337. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  61338. * @returns The render target texture if the shadow map is present otherwise, null
  61339. */
  61340. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  61341. if (this._shadowMap2) {
  61342. return this._shadowMap2;
  61343. }
  61344. return this._shadowMap;
  61345. };
  61346. /**
  61347. * Helper function to add a mesh and its descendants to the list of shadow casters.
  61348. * @param mesh Mesh to add
  61349. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  61350. * @returns the Shadow Generator itself
  61351. */
  61352. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  61353. if (includeDescendants === void 0) { includeDescendants = true; }
  61354. if (!this._shadowMap) {
  61355. return this;
  61356. }
  61357. if (!this._shadowMap.renderList) {
  61358. this._shadowMap.renderList = [];
  61359. }
  61360. this._shadowMap.renderList.push(mesh);
  61361. if (includeDescendants) {
  61362. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  61363. }
  61364. return this;
  61365. var _a;
  61366. };
  61367. /**
  61368. * Helper function to remove a mesh and its descendants from the list of shadow casters
  61369. * @param mesh Mesh to remove
  61370. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  61371. * @returns the Shadow Generator itself
  61372. */
  61373. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  61374. if (includeDescendants === void 0) { includeDescendants = true; }
  61375. if (!this._shadowMap || !this._shadowMap.renderList) {
  61376. return this;
  61377. }
  61378. var index = this._shadowMap.renderList.indexOf(mesh);
  61379. if (index !== -1) {
  61380. this._shadowMap.renderList.splice(index, 1);
  61381. }
  61382. if (includeDescendants) {
  61383. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  61384. var child = _a[_i];
  61385. this.removeShadowCaster(child);
  61386. }
  61387. }
  61388. return this;
  61389. };
  61390. /**
  61391. * Returns the associated light object.
  61392. * @returns the light generating the shadow
  61393. */
  61394. ShadowGenerator.prototype.getLight = function () {
  61395. return this._light;
  61396. };
  61397. ShadowGenerator.prototype._initializeGenerator = function () {
  61398. this._light._markMeshesAsLightDirty();
  61399. this._initializeShadowMap();
  61400. };
  61401. ShadowGenerator.prototype._initializeShadowMap = function () {
  61402. var _this = this;
  61403. // Render target
  61404. var engine = this._scene.getEngine();
  61405. if (engine.webGLVersion > 1) {
  61406. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  61407. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  61408. }
  61409. else {
  61410. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  61411. }
  61412. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61413. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61414. this._shadowMap.anisotropicFilteringLevel = 1;
  61415. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  61416. this._shadowMap.renderParticles = false;
  61417. this._shadowMap.ignoreCameraViewport = true;
  61418. // Record Face Index before render.
  61419. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  61420. _this._currentFaceIndex = faceIndex;
  61421. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  61422. engine.setColorWrite(false);
  61423. }
  61424. });
  61425. // Custom render function.
  61426. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  61427. // Blur if required afer render.
  61428. this._shadowMap.onAfterUnbindObservable.add(function () {
  61429. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  61430. engine.setColorWrite(true);
  61431. }
  61432. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  61433. return;
  61434. }
  61435. var shadowMap = _this.getShadowMapForRendering();
  61436. if (shadowMap) {
  61437. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  61438. }
  61439. });
  61440. // Clear according to the chosen filter.
  61441. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  61442. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  61443. this._shadowMap.onClearObservable.add(function (engine) {
  61444. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  61445. engine.clear(clearOne, false, true, false);
  61446. }
  61447. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  61448. engine.clear(clearZero, true, true, false);
  61449. }
  61450. else {
  61451. engine.clear(clearOne, true, true, false);
  61452. }
  61453. });
  61454. };
  61455. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  61456. var _this = this;
  61457. var engine = this._scene.getEngine();
  61458. var targetSize = this._mapSize / this.blurScale;
  61459. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  61460. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  61461. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61462. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  61463. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  61464. }
  61465. if (this.useKernelBlur) {
  61466. 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);
  61467. this._kernelBlurXPostprocess.width = targetSize;
  61468. this._kernelBlurXPostprocess.height = targetSize;
  61469. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  61470. effect.setTexture("textureSampler", _this._shadowMap);
  61471. });
  61472. 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);
  61473. this._kernelBlurXPostprocess.autoClear = false;
  61474. this._kernelBlurYPostprocess.autoClear = false;
  61475. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  61476. this._kernelBlurXPostprocess.packedFloat = true;
  61477. this._kernelBlurYPostprocess.packedFloat = true;
  61478. }
  61479. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  61480. }
  61481. else {
  61482. 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);
  61483. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  61484. effect.setFloat2("screenSize", targetSize, targetSize);
  61485. effect.setTexture("textureSampler", _this._shadowMap);
  61486. });
  61487. this._boxBlurPostprocess.autoClear = false;
  61488. this._blurPostProcesses = [this._boxBlurPostprocess];
  61489. }
  61490. };
  61491. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  61492. var index;
  61493. var engine = this._scene.getEngine();
  61494. if (depthOnlySubMeshes.length) {
  61495. engine.setColorWrite(false);
  61496. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  61497. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  61498. }
  61499. engine.setColorWrite(true);
  61500. }
  61501. for (index = 0; index < opaqueSubMeshes.length; index++) {
  61502. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  61503. }
  61504. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  61505. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  61506. }
  61507. if (this._transparencyShadow) {
  61508. for (index = 0; index < transparentSubMeshes.length; index++) {
  61509. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  61510. }
  61511. }
  61512. };
  61513. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  61514. var _this = this;
  61515. var mesh = subMesh.getRenderingMesh();
  61516. var scene = this._scene;
  61517. var engine = scene.getEngine();
  61518. var material = subMesh.getMaterial();
  61519. if (!material) {
  61520. return;
  61521. }
  61522. // Culling
  61523. engine.setState(material.backFaceCulling);
  61524. // Managing instances
  61525. var batch = mesh._getInstancesRenderList(subMesh._id);
  61526. if (batch.mustReturn) {
  61527. return;
  61528. }
  61529. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  61530. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  61531. engine.enableEffect(this._effect);
  61532. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  61533. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  61534. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  61535. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  61536. this._effect.setVector3("lightData", this._cachedDirection);
  61537. }
  61538. else {
  61539. this._effect.setVector3("lightData", this._cachedPosition);
  61540. }
  61541. if (scene.activeCamera) {
  61542. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  61543. }
  61544. // Alpha test
  61545. if (material && material.needAlphaTesting()) {
  61546. var alphaTexture = material.getAlphaTestTexture();
  61547. if (alphaTexture) {
  61548. this._effect.setTexture("diffuseSampler", alphaTexture);
  61549. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  61550. }
  61551. }
  61552. // Bones
  61553. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  61554. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  61555. }
  61556. if (this.forceBackFacesOnly) {
  61557. engine.setState(true, 0, false, true);
  61558. }
  61559. // Draw
  61560. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  61561. if (this.forceBackFacesOnly) {
  61562. engine.setState(true, 0, false, false);
  61563. }
  61564. }
  61565. else {
  61566. // Need to reset refresh rate of the shadowMap
  61567. if (this._shadowMap) {
  61568. this._shadowMap.resetRefreshCounter();
  61569. }
  61570. }
  61571. };
  61572. ShadowGenerator.prototype._applyFilterValues = function () {
  61573. if (!this._shadowMap) {
  61574. return;
  61575. }
  61576. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  61577. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  61578. }
  61579. else {
  61580. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  61581. }
  61582. };
  61583. /**
  61584. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  61585. * @param onCompiled Callback triggered at the and of the effects compilation
  61586. * @param options Sets of optional options forcing the compilation with different modes
  61587. */
  61588. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  61589. var _this = this;
  61590. var localOptions = __assign({ useInstances: false }, options);
  61591. var shadowMap = this.getShadowMap();
  61592. if (!shadowMap) {
  61593. if (onCompiled) {
  61594. onCompiled(this);
  61595. }
  61596. return;
  61597. }
  61598. var renderList = shadowMap.renderList;
  61599. if (!renderList) {
  61600. if (onCompiled) {
  61601. onCompiled(this);
  61602. }
  61603. return;
  61604. }
  61605. var subMeshes = new Array();
  61606. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  61607. var mesh = renderList_1[_i];
  61608. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  61609. }
  61610. if (subMeshes.length === 0) {
  61611. if (onCompiled) {
  61612. onCompiled(this);
  61613. }
  61614. return;
  61615. }
  61616. var currentIndex = 0;
  61617. var checkReady = function () {
  61618. if (!_this._scene || !_this._scene.getEngine()) {
  61619. return;
  61620. }
  61621. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  61622. currentIndex++;
  61623. if (currentIndex >= subMeshes.length) {
  61624. if (onCompiled) {
  61625. onCompiled(_this);
  61626. }
  61627. return;
  61628. }
  61629. }
  61630. setTimeout(checkReady, 16);
  61631. };
  61632. checkReady();
  61633. };
  61634. /**
  61635. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  61636. * @param options Sets of optional options forcing the compilation with different modes
  61637. * @returns A promise that resolves when the compilation completes
  61638. */
  61639. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  61640. var _this = this;
  61641. return new Promise(function (resolve) {
  61642. _this.forceCompilation(function () {
  61643. resolve();
  61644. }, options);
  61645. });
  61646. };
  61647. /**
  61648. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  61649. * @param subMesh The submesh we want to render in the shadow map
  61650. * @param useInstances Defines wether will draw in the map using instances
  61651. * @returns true if ready otherwise, false
  61652. */
  61653. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  61654. var defines = [];
  61655. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  61656. defines.push("#define FLOAT");
  61657. }
  61658. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  61659. defines.push("#define ESM");
  61660. }
  61661. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  61662. defines.push("#define DEPTHTEXTURE");
  61663. }
  61664. var attribs = [BABYLON.VertexBuffer.PositionKind];
  61665. var mesh = subMesh.getMesh();
  61666. var material = subMesh.getMaterial();
  61667. // Normal bias.
  61668. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  61669. attribs.push(BABYLON.VertexBuffer.NormalKind);
  61670. defines.push("#define NORMAL");
  61671. if (mesh.nonUniformScaling) {
  61672. defines.push("#define NONUNIFORMSCALING");
  61673. }
  61674. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  61675. defines.push("#define DIRECTIONINLIGHTDATA");
  61676. }
  61677. }
  61678. // Alpha test
  61679. if (material && material.needAlphaTesting()) {
  61680. var alphaTexture = material.getAlphaTestTexture();
  61681. if (alphaTexture) {
  61682. defines.push("#define ALPHATEST");
  61683. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  61684. attribs.push(BABYLON.VertexBuffer.UVKind);
  61685. defines.push("#define UV1");
  61686. }
  61687. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  61688. if (alphaTexture.coordinatesIndex === 1) {
  61689. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  61690. defines.push("#define UV2");
  61691. }
  61692. }
  61693. }
  61694. }
  61695. // Bones
  61696. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  61697. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  61698. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  61699. if (mesh.numBoneInfluencers > 4) {
  61700. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  61701. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  61702. }
  61703. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  61704. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  61705. }
  61706. else {
  61707. defines.push("#define NUM_BONE_INFLUENCERS 0");
  61708. }
  61709. // Instances
  61710. if (useInstances) {
  61711. defines.push("#define INSTANCES");
  61712. attribs.push("world0");
  61713. attribs.push("world1");
  61714. attribs.push("world2");
  61715. attribs.push("world3");
  61716. }
  61717. // Get correct effect
  61718. var join = defines.join("\n");
  61719. if (this._cachedDefines !== join) {
  61720. this._cachedDefines = join;
  61721. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  61722. }
  61723. if (!this._effect.isReady()) {
  61724. return false;
  61725. }
  61726. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  61727. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  61728. this._initializeBlurRTTAndPostProcesses();
  61729. }
  61730. }
  61731. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  61732. return false;
  61733. }
  61734. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  61735. return false;
  61736. }
  61737. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  61738. return false;
  61739. }
  61740. return true;
  61741. };
  61742. /**
  61743. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  61744. * @param defines Defines of the material we want to update
  61745. * @param lightIndex Index of the light in the enabled light list of the material
  61746. */
  61747. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  61748. var scene = this._scene;
  61749. var light = this._light;
  61750. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  61751. return;
  61752. }
  61753. defines["SHADOW" + lightIndex] = true;
  61754. if (this.useContactHardeningShadow) {
  61755. defines["SHADOWPCSS" + lightIndex] = true;
  61756. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  61757. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  61758. }
  61759. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  61760. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  61761. }
  61762. // else default to high.
  61763. }
  61764. if (this.usePercentageCloserFiltering) {
  61765. defines["SHADOWPCF" + lightIndex] = true;
  61766. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  61767. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  61768. }
  61769. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  61770. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  61771. }
  61772. // else default to high.
  61773. }
  61774. else if (this.usePoissonSampling) {
  61775. defines["SHADOWPOISSON" + lightIndex] = true;
  61776. }
  61777. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  61778. defines["SHADOWESM" + lightIndex] = true;
  61779. }
  61780. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  61781. defines["SHADOWCLOSEESM" + lightIndex] = true;
  61782. }
  61783. if (light.needCube()) {
  61784. defines["SHADOWCUBE" + lightIndex] = true;
  61785. }
  61786. };
  61787. /**
  61788. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  61789. * defined in the generator but impacting the effect).
  61790. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  61791. * @param effect The effect we are binfing the information for
  61792. */
  61793. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  61794. var light = this._light;
  61795. var scene = this._scene;
  61796. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  61797. return;
  61798. }
  61799. var camera = scene.activeCamera;
  61800. if (!camera) {
  61801. return;
  61802. }
  61803. var shadowMap = this.getShadowMap();
  61804. if (!shadowMap) {
  61805. return;
  61806. }
  61807. if (!light.needCube()) {
  61808. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  61809. }
  61810. // Only PCF uses depth stencil texture.
  61811. if (this._filter === ShadowGenerator.FILTER_PCF) {
  61812. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  61813. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  61814. }
  61815. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  61816. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  61817. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  61818. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  61819. }
  61820. else {
  61821. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  61822. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  61823. }
  61824. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  61825. };
  61826. /**
  61827. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  61828. * (eq to shadow prjection matrix * light transform matrix)
  61829. * @returns The transform matrix used to create the shadow map
  61830. */
  61831. ShadowGenerator.prototype.getTransformMatrix = function () {
  61832. var scene = this._scene;
  61833. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  61834. return this._transformMatrix;
  61835. }
  61836. this._currentRenderID = scene.getRenderId();
  61837. this._currentFaceIndexCache = this._currentFaceIndex;
  61838. var lightPosition = this._light.position;
  61839. if (this._light.computeTransformedInformation()) {
  61840. lightPosition = this._light.transformedPosition;
  61841. }
  61842. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  61843. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  61844. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  61845. }
  61846. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  61847. this._cachedPosition.copyFrom(lightPosition);
  61848. this._cachedDirection.copyFrom(this._lightDirection);
  61849. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  61850. var shadowMap = this.getShadowMap();
  61851. if (shadowMap) {
  61852. var renderList = shadowMap.renderList;
  61853. if (renderList) {
  61854. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  61855. }
  61856. }
  61857. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  61858. }
  61859. return this._transformMatrix;
  61860. };
  61861. /**
  61862. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  61863. * Cube and 2D textures for instance.
  61864. */
  61865. ShadowGenerator.prototype.recreateShadowMap = function () {
  61866. var shadowMap = this._shadowMap;
  61867. if (!shadowMap) {
  61868. return;
  61869. }
  61870. // Track render list.
  61871. var renderList = shadowMap.renderList;
  61872. // Clean up existing data.
  61873. this._disposeRTTandPostProcesses();
  61874. // Reinitializes.
  61875. this._initializeGenerator();
  61876. // Reaffect the filter to ensure a correct fallback if necessary.
  61877. this.filter = this.filter;
  61878. // Reaffect the filter.
  61879. this._applyFilterValues();
  61880. // Reaffect Render List.
  61881. this._shadowMap.renderList = renderList;
  61882. };
  61883. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  61884. if (this._shadowMap2) {
  61885. this._shadowMap2.dispose();
  61886. this._shadowMap2 = null;
  61887. }
  61888. if (this._boxBlurPostprocess) {
  61889. this._boxBlurPostprocess.dispose();
  61890. this._boxBlurPostprocess = null;
  61891. }
  61892. if (this._kernelBlurXPostprocess) {
  61893. this._kernelBlurXPostprocess.dispose();
  61894. this._kernelBlurXPostprocess = null;
  61895. }
  61896. if (this._kernelBlurYPostprocess) {
  61897. this._kernelBlurYPostprocess.dispose();
  61898. this._kernelBlurYPostprocess = null;
  61899. }
  61900. this._blurPostProcesses = [];
  61901. };
  61902. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  61903. if (this._shadowMap) {
  61904. this._shadowMap.dispose();
  61905. this._shadowMap = null;
  61906. }
  61907. this._disposeBlurPostProcesses();
  61908. };
  61909. /**
  61910. * Disposes the ShadowGenerator.
  61911. * Returns nothing.
  61912. */
  61913. ShadowGenerator.prototype.dispose = function () {
  61914. this._disposeRTTandPostProcesses();
  61915. if (this._light) {
  61916. this._light._shadowGenerator = null;
  61917. this._light._markMeshesAsLightDirty();
  61918. }
  61919. };
  61920. /**
  61921. * Serializes the shadow generator setup to a json object.
  61922. * @returns The serialized JSON object
  61923. */
  61924. ShadowGenerator.prototype.serialize = function () {
  61925. var serializationObject = {};
  61926. var shadowMap = this.getShadowMap();
  61927. if (!shadowMap) {
  61928. return serializationObject;
  61929. }
  61930. serializationObject.lightId = this._light.id;
  61931. serializationObject.mapSize = shadowMap.getRenderSize();
  61932. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  61933. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  61934. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  61935. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  61936. serializationObject.usePoissonSampling = this.usePoissonSampling;
  61937. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  61938. serializationObject.depthScale = this.depthScale;
  61939. serializationObject.darkness = this.getDarkness();
  61940. serializationObject.blurBoxOffset = this.blurBoxOffset;
  61941. serializationObject.blurKernel = this.blurKernel;
  61942. serializationObject.blurScale = this.blurScale;
  61943. serializationObject.useKernelBlur = this.useKernelBlur;
  61944. serializationObject.transparencyShadow = this._transparencyShadow;
  61945. serializationObject.bias = this.bias;
  61946. serializationObject.normalBias = this.normalBias;
  61947. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  61948. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  61949. serializationObject.filteringQuality = this.filteringQuality;
  61950. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  61951. serializationObject.renderList = [];
  61952. if (shadowMap.renderList) {
  61953. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  61954. var mesh = shadowMap.renderList[meshIndex];
  61955. serializationObject.renderList.push(mesh.id);
  61956. }
  61957. }
  61958. return serializationObject;
  61959. };
  61960. /**
  61961. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  61962. * @param parsedShadowGenerator The JSON object to parse
  61963. * @param scene The scene to create the shadow map for
  61964. * @returns The parsed shadow generator
  61965. */
  61966. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  61967. //casting to point light, as light is missing the position attr and typescript complains.
  61968. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  61969. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  61970. var shadowMap = shadowGenerator.getShadowMap();
  61971. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  61972. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  61973. meshes.forEach(function (mesh) {
  61974. if (!shadowMap) {
  61975. return;
  61976. }
  61977. if (!shadowMap.renderList) {
  61978. shadowMap.renderList = [];
  61979. }
  61980. shadowMap.renderList.push(mesh);
  61981. });
  61982. }
  61983. if (parsedShadowGenerator.usePoissonSampling) {
  61984. shadowGenerator.usePoissonSampling = true;
  61985. }
  61986. else if (parsedShadowGenerator.useExponentialShadowMap) {
  61987. shadowGenerator.useExponentialShadowMap = true;
  61988. }
  61989. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  61990. shadowGenerator.useBlurExponentialShadowMap = true;
  61991. }
  61992. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  61993. shadowGenerator.useCloseExponentialShadowMap = true;
  61994. }
  61995. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  61996. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  61997. }
  61998. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  61999. shadowGenerator.usePercentageCloserFiltering = true;
  62000. }
  62001. else if (parsedShadowGenerator.useContactHardeningShadow) {
  62002. shadowGenerator.useContactHardeningShadow = true;
  62003. }
  62004. if (parsedShadowGenerator.filteringQuality) {
  62005. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  62006. }
  62007. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  62008. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  62009. }
  62010. else if (parsedShadowGenerator.useVarianceShadowMap) {
  62011. shadowGenerator.useExponentialShadowMap = true;
  62012. }
  62013. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  62014. shadowGenerator.useBlurExponentialShadowMap = true;
  62015. }
  62016. if (parsedShadowGenerator.depthScale) {
  62017. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  62018. }
  62019. if (parsedShadowGenerator.blurScale) {
  62020. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  62021. }
  62022. if (parsedShadowGenerator.blurBoxOffset) {
  62023. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  62024. }
  62025. if (parsedShadowGenerator.useKernelBlur) {
  62026. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  62027. }
  62028. if (parsedShadowGenerator.blurKernel) {
  62029. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  62030. }
  62031. if (parsedShadowGenerator.bias !== undefined) {
  62032. shadowGenerator.bias = parsedShadowGenerator.bias;
  62033. }
  62034. if (parsedShadowGenerator.normalBias !== undefined) {
  62035. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  62036. }
  62037. if (parsedShadowGenerator.darkness) {
  62038. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  62039. }
  62040. if (parsedShadowGenerator.transparencyShadow) {
  62041. shadowGenerator.setTransparencyShadow(true);
  62042. }
  62043. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  62044. return shadowGenerator;
  62045. };
  62046. /**
  62047. * Shadow generator mode None: no filtering applied.
  62048. */
  62049. ShadowGenerator.FILTER_NONE = 0;
  62050. /**
  62051. * Shadow generator mode ESM: Exponential Shadow Mapping.
  62052. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  62053. */
  62054. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  62055. /**
  62056. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  62057. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  62058. */
  62059. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  62060. /**
  62061. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  62062. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  62063. */
  62064. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  62065. /**
  62066. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  62067. * edge artifacts on steep falloff.
  62068. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  62069. */
  62070. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  62071. /**
  62072. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  62073. * edge artifacts on steep falloff.
  62074. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  62075. */
  62076. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  62077. /**
  62078. * Shadow generator mode PCF: Percentage Closer Filtering
  62079. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  62080. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  62081. */
  62082. ShadowGenerator.FILTER_PCF = 6;
  62083. /**
  62084. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  62085. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  62086. * Contact Hardening
  62087. */
  62088. ShadowGenerator.FILTER_PCSS = 7;
  62089. /**
  62090. * Reserved for PCF and PCSS
  62091. * Highest Quality.
  62092. *
  62093. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  62094. *
  62095. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  62096. */
  62097. ShadowGenerator.QUALITY_HIGH = 0;
  62098. /**
  62099. * Reserved for PCF and PCSS
  62100. * Good tradeoff for quality/perf cross devices
  62101. *
  62102. * Execute PCF on a 3*3 kernel.
  62103. *
  62104. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  62105. */
  62106. ShadowGenerator.QUALITY_MEDIUM = 1;
  62107. /**
  62108. * Reserved for PCF and PCSS
  62109. * The lowest quality but the fastest.
  62110. *
  62111. * Execute PCF on a 1*1 kernel.
  62112. *
  62113. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  62114. */
  62115. ShadowGenerator.QUALITY_LOW = 2;
  62116. return ShadowGenerator;
  62117. }());
  62118. BABYLON.ShadowGenerator = ShadowGenerator;
  62119. })(BABYLON || (BABYLON = {}));
  62120. //# sourceMappingURL=babylon.shadowGenerator.js.map
  62121. "use strict";
  62122. var BABYLON;
  62123. (function (BABYLON) {
  62124. var DefaultLoadingScreen = /** @class */ (function () {
  62125. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  62126. if (_loadingText === void 0) { _loadingText = ""; }
  62127. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  62128. var _this = this;
  62129. this._renderingCanvas = _renderingCanvas;
  62130. this._loadingText = _loadingText;
  62131. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  62132. // Resize
  62133. this._resizeLoadingUI = function () {
  62134. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  62135. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  62136. if (!_this._loadingDiv) {
  62137. return;
  62138. }
  62139. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  62140. _this._loadingDiv.style.left = canvasRect.left + "px";
  62141. _this._loadingDiv.style.top = canvasRect.top + "px";
  62142. _this._loadingDiv.style.width = canvasRect.width + "px";
  62143. _this._loadingDiv.style.height = canvasRect.height + "px";
  62144. };
  62145. }
  62146. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  62147. if (this._loadingDiv) {
  62148. // Do not add a loading screen if there is already one
  62149. return;
  62150. }
  62151. this._loadingDiv = document.createElement("div");
  62152. this._loadingDiv.id = "babylonjsLoadingDiv";
  62153. this._loadingDiv.style.opacity = "0";
  62154. this._loadingDiv.style.transition = "opacity 1.5s ease";
  62155. this._loadingDiv.style.pointerEvents = "none";
  62156. // Loading text
  62157. this._loadingTextDiv = document.createElement("div");
  62158. this._loadingTextDiv.style.position = "absolute";
  62159. this._loadingTextDiv.style.left = "0";
  62160. this._loadingTextDiv.style.top = "50%";
  62161. this._loadingTextDiv.style.marginTop = "80px";
  62162. this._loadingTextDiv.style.width = "100%";
  62163. this._loadingTextDiv.style.height = "20px";
  62164. this._loadingTextDiv.style.fontFamily = "Arial";
  62165. this._loadingTextDiv.style.fontSize = "14px";
  62166. this._loadingTextDiv.style.color = "white";
  62167. this._loadingTextDiv.style.textAlign = "center";
  62168. this._loadingTextDiv.innerHTML = "Loading";
  62169. this._loadingDiv.appendChild(this._loadingTextDiv);
  62170. //set the predefined text
  62171. this._loadingTextDiv.innerHTML = this._loadingText;
  62172. // Generating keyframes
  62173. var style = document.createElement('style');
  62174. style.type = 'text/css';
  62175. 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 }";
  62176. style.innerHTML = keyFrames;
  62177. document.getElementsByTagName('head')[0].appendChild(style);
  62178. // Loading img
  62179. var imgBack = new Image();
  62180. 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";
  62181. imgBack.style.position = "absolute";
  62182. imgBack.style.left = "50%";
  62183. imgBack.style.top = "50%";
  62184. imgBack.style.marginLeft = "-60px";
  62185. imgBack.style.marginTop = "-60px";
  62186. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  62187. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  62188. imgBack.style.transformOrigin = "50% 50%";
  62189. imgBack.style.webkitTransformOrigin = "50% 50%";
  62190. this._loadingDiv.appendChild(imgBack);
  62191. this._resizeLoadingUI();
  62192. window.addEventListener("resize", this._resizeLoadingUI);
  62193. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  62194. document.body.appendChild(this._loadingDiv);
  62195. this._loadingDiv.style.opacity = "1";
  62196. };
  62197. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  62198. var _this = this;
  62199. if (!this._loadingDiv) {
  62200. return;
  62201. }
  62202. var onTransitionEnd = function () {
  62203. if (!_this._loadingDiv) {
  62204. return;
  62205. }
  62206. document.body.removeChild(_this._loadingDiv);
  62207. window.removeEventListener("resize", _this._resizeLoadingUI);
  62208. _this._loadingDiv = null;
  62209. };
  62210. this._loadingDiv.style.opacity = "0";
  62211. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  62212. };
  62213. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  62214. set: function (text) {
  62215. this._loadingText = text;
  62216. if (this._loadingTextDiv) {
  62217. this._loadingTextDiv.innerHTML = this._loadingText;
  62218. }
  62219. },
  62220. enumerable: true,
  62221. configurable: true
  62222. });
  62223. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  62224. get: function () {
  62225. return this._loadingDivBackgroundColor;
  62226. },
  62227. set: function (color) {
  62228. this._loadingDivBackgroundColor = color;
  62229. if (!this._loadingDiv) {
  62230. return;
  62231. }
  62232. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  62233. },
  62234. enumerable: true,
  62235. configurable: true
  62236. });
  62237. return DefaultLoadingScreen;
  62238. }());
  62239. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  62240. })(BABYLON || (BABYLON = {}));
  62241. //# sourceMappingURL=babylon.loadingScreen.js.map
  62242. "use strict";
  62243. var BABYLON;
  62244. (function (BABYLON) {
  62245. var SceneLoaderProgressEvent = /** @class */ (function () {
  62246. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  62247. this.lengthComputable = lengthComputable;
  62248. this.loaded = loaded;
  62249. this.total = total;
  62250. }
  62251. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  62252. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  62253. };
  62254. return SceneLoaderProgressEvent;
  62255. }());
  62256. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  62257. var SceneLoader = /** @class */ (function () {
  62258. function SceneLoader() {
  62259. }
  62260. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  62261. get: function () {
  62262. return 0;
  62263. },
  62264. enumerable: true,
  62265. configurable: true
  62266. });
  62267. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  62268. get: function () {
  62269. return 1;
  62270. },
  62271. enumerable: true,
  62272. configurable: true
  62273. });
  62274. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  62275. get: function () {
  62276. return 2;
  62277. },
  62278. enumerable: true,
  62279. configurable: true
  62280. });
  62281. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  62282. get: function () {
  62283. return 3;
  62284. },
  62285. enumerable: true,
  62286. configurable: true
  62287. });
  62288. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  62289. get: function () {
  62290. return SceneLoader._ForceFullSceneLoadingForIncremental;
  62291. },
  62292. set: function (value) {
  62293. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  62294. },
  62295. enumerable: true,
  62296. configurable: true
  62297. });
  62298. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  62299. get: function () {
  62300. return SceneLoader._ShowLoadingScreen;
  62301. },
  62302. set: function (value) {
  62303. SceneLoader._ShowLoadingScreen = value;
  62304. },
  62305. enumerable: true,
  62306. configurable: true
  62307. });
  62308. Object.defineProperty(SceneLoader, "loggingLevel", {
  62309. get: function () {
  62310. return SceneLoader._loggingLevel;
  62311. },
  62312. set: function (value) {
  62313. SceneLoader._loggingLevel = value;
  62314. },
  62315. enumerable: true,
  62316. configurable: true
  62317. });
  62318. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  62319. get: function () {
  62320. return SceneLoader._CleanBoneMatrixWeights;
  62321. },
  62322. set: function (value) {
  62323. SceneLoader._CleanBoneMatrixWeights = value;
  62324. },
  62325. enumerable: true,
  62326. configurable: true
  62327. });
  62328. SceneLoader._getDefaultPlugin = function () {
  62329. return SceneLoader._registeredPlugins[".babylon"];
  62330. };
  62331. SceneLoader._getPluginForExtension = function (extension) {
  62332. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  62333. if (registeredPlugin) {
  62334. return registeredPlugin;
  62335. }
  62336. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  62337. return SceneLoader._getDefaultPlugin();
  62338. };
  62339. SceneLoader._getPluginForDirectLoad = function (data) {
  62340. for (var extension in SceneLoader._registeredPlugins) {
  62341. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  62342. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  62343. return SceneLoader._registeredPlugins[extension];
  62344. }
  62345. }
  62346. return SceneLoader._getDefaultPlugin();
  62347. };
  62348. SceneLoader._getPluginForFilename = function (sceneFilename) {
  62349. if (sceneFilename.name) {
  62350. sceneFilename = sceneFilename.name;
  62351. }
  62352. var queryStringPosition = sceneFilename.indexOf("?");
  62353. if (queryStringPosition !== -1) {
  62354. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  62355. }
  62356. var dotPosition = sceneFilename.lastIndexOf(".");
  62357. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  62358. return SceneLoader._getPluginForExtension(extension);
  62359. };
  62360. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  62361. SceneLoader._getDirectLoad = function (sceneFilename) {
  62362. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  62363. return sceneFilename.substr(5);
  62364. }
  62365. return null;
  62366. };
  62367. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  62368. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  62369. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  62370. var plugin;
  62371. if (registeredPlugin.plugin.createPlugin) {
  62372. plugin = registeredPlugin.plugin.createPlugin();
  62373. }
  62374. else {
  62375. plugin = registeredPlugin.plugin;
  62376. }
  62377. var useArrayBuffer = registeredPlugin.isBinary;
  62378. var database;
  62379. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  62380. var dataCallback = function (data, responseURL) {
  62381. if (scene.isDisposed) {
  62382. onError("Scene has been disposed");
  62383. return;
  62384. }
  62385. scene.database = database;
  62386. onSuccess(plugin, data, responseURL);
  62387. };
  62388. var request = null;
  62389. var pluginDisposed = false;
  62390. var onDisposeObservable = plugin.onDisposeObservable;
  62391. if (onDisposeObservable) {
  62392. onDisposeObservable.add(function () {
  62393. pluginDisposed = true;
  62394. if (request) {
  62395. request.abort();
  62396. request = null;
  62397. }
  62398. onDispose();
  62399. });
  62400. }
  62401. var manifestChecked = function () {
  62402. if (pluginDisposed) {
  62403. return;
  62404. }
  62405. var url = rootUrl + sceneFilename;
  62406. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  62407. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  62408. } : undefined, database, useArrayBuffer, function (request, exception) {
  62409. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  62410. });
  62411. };
  62412. if (directLoad) {
  62413. dataCallback(directLoad);
  62414. return plugin;
  62415. }
  62416. if (rootUrl.indexOf("file:") === -1) {
  62417. if (scene.getEngine().enableOfflineSupport) {
  62418. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  62419. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  62420. }
  62421. else {
  62422. manifestChecked();
  62423. }
  62424. }
  62425. else {
  62426. var fileOrString = sceneFilename;
  62427. if (fileOrString.name) {
  62428. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  62429. }
  62430. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  62431. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  62432. }
  62433. else {
  62434. onError("Unable to find file named " + sceneFilename);
  62435. }
  62436. }
  62437. return plugin;
  62438. };
  62439. // Public functions
  62440. SceneLoader.GetPluginForExtension = function (extension) {
  62441. return SceneLoader._getPluginForExtension(extension).plugin;
  62442. };
  62443. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  62444. return !!SceneLoader._registeredPlugins[extension];
  62445. };
  62446. SceneLoader.RegisterPlugin = function (plugin) {
  62447. if (typeof plugin.extensions === "string") {
  62448. var extension = plugin.extensions;
  62449. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  62450. plugin: plugin,
  62451. isBinary: false
  62452. };
  62453. }
  62454. else {
  62455. var extensions = plugin.extensions;
  62456. Object.keys(extensions).forEach(function (extension) {
  62457. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  62458. plugin: plugin,
  62459. isBinary: extensions[extension].isBinary
  62460. };
  62461. });
  62462. }
  62463. };
  62464. /**
  62465. * Import meshes into a scene
  62466. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  62467. * @param rootUrl a string that defines the root url for scene and resources
  62468. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62469. * @param scene the instance of BABYLON.Scene to append to
  62470. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  62471. * @param onProgress a callback with a progress event for each file being loaded
  62472. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  62473. * @param pluginExtension the extension used to determine the plugin
  62474. * @returns The loaded plugin
  62475. */
  62476. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  62477. if (onSuccess === void 0) { onSuccess = null; }
  62478. if (onProgress === void 0) { onProgress = null; }
  62479. if (onError === void 0) { onError = null; }
  62480. if (pluginExtension === void 0) { pluginExtension = null; }
  62481. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  62482. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  62483. return null;
  62484. }
  62485. var loadingToken = {};
  62486. scene._addPendingData(loadingToken);
  62487. var disposeHandler = function () {
  62488. scene._removePendingData(loadingToken);
  62489. };
  62490. var errorHandler = function (message, exception) {
  62491. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  62492. if (onError) {
  62493. onError(scene, errorMessage, exception);
  62494. }
  62495. else {
  62496. BABYLON.Tools.Error(errorMessage);
  62497. // should the exception be thrown?
  62498. }
  62499. disposeHandler();
  62500. };
  62501. var progressHandler = onProgress ? function (event) {
  62502. try {
  62503. onProgress(event);
  62504. }
  62505. catch (e) {
  62506. errorHandler("Error in onProgress callback", e);
  62507. }
  62508. } : undefined;
  62509. var successHandler = function (meshes, particleSystems, skeletons) {
  62510. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  62511. if (onSuccess) {
  62512. try {
  62513. onSuccess(meshes, particleSystems, skeletons);
  62514. }
  62515. catch (e) {
  62516. errorHandler("Error in onSuccess callback", e);
  62517. }
  62518. }
  62519. scene._removePendingData(loadingToken);
  62520. };
  62521. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  62522. if (plugin.rewriteRootURL) {
  62523. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  62524. }
  62525. if (sceneFilename === "") {
  62526. if (sceneFilename === "") {
  62527. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  62528. }
  62529. }
  62530. if (plugin.importMesh) {
  62531. var syncedPlugin = plugin;
  62532. var meshes = new Array();
  62533. var particleSystems = new Array();
  62534. var skeletons = new Array();
  62535. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  62536. return;
  62537. }
  62538. scene.loadingPluginName = plugin.name;
  62539. successHandler(meshes, particleSystems, skeletons);
  62540. }
  62541. else {
  62542. var asyncedPlugin = plugin;
  62543. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  62544. scene.loadingPluginName = plugin.name;
  62545. successHandler(result.meshes, result.particleSystems, result.skeletons);
  62546. }).catch(function (error) {
  62547. errorHandler(error.message, error);
  62548. });
  62549. }
  62550. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  62551. };
  62552. /**
  62553. * Import meshes into a scene
  62554. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  62555. * @param rootUrl a string that defines the root url for scene and resources
  62556. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62557. * @param scene the instance of BABYLON.Scene to append to
  62558. * @param onProgress a callback with a progress event for each file being loaded
  62559. * @param pluginExtension the extension used to determine the plugin
  62560. * @returns The loaded list of imported meshes, particleSystems, and skeletons
  62561. */
  62562. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  62563. if (onProgress === void 0) { onProgress = null; }
  62564. if (pluginExtension === void 0) { pluginExtension = null; }
  62565. return new Promise(function (resolve, reject) {
  62566. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  62567. resolve({
  62568. meshes: meshes,
  62569. particleSystems: particleSystems,
  62570. skeletons: skeletons
  62571. });
  62572. }, onProgress, function (scene, message, exception) {
  62573. reject(exception || new Error(message));
  62574. });
  62575. });
  62576. };
  62577. /**
  62578. * Load a scene
  62579. * @param rootUrl a string that defines the root url for scene and resources
  62580. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62581. * @param engine is the instance of BABYLON.Engine to use to create the scene
  62582. * @param onSuccess a callback with the scene when import succeeds
  62583. * @param onProgress a callback with a progress event for each file being loaded
  62584. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  62585. * @param pluginExtension the extension used to determine the plugin
  62586. * @returns The loaded plugin
  62587. */
  62588. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  62589. if (onSuccess === void 0) { onSuccess = null; }
  62590. if (onProgress === void 0) { onProgress = null; }
  62591. if (onError === void 0) { onError = null; }
  62592. if (pluginExtension === void 0) { pluginExtension = null; }
  62593. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  62594. };
  62595. /**
  62596. * Load a scene
  62597. * @param rootUrl a string that defines the root url for scene and resources
  62598. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62599. * @param engine is the instance of BABYLON.Engine to use to create the scene
  62600. * @param onProgress a callback with a progress event for each file being loaded
  62601. * @param pluginExtension the extension used to determine the plugin
  62602. * @returns The loaded scene
  62603. */
  62604. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  62605. if (onProgress === void 0) { onProgress = null; }
  62606. if (pluginExtension === void 0) { pluginExtension = null; }
  62607. return new Promise(function (resolve, reject) {
  62608. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  62609. resolve(scene);
  62610. }, onProgress, function (scene, message, exception) {
  62611. reject(exception || new Error(message));
  62612. }, pluginExtension);
  62613. });
  62614. };
  62615. /**
  62616. * Append a scene
  62617. * @param rootUrl a string that defines the root url for scene and resources
  62618. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62619. * @param scene is the instance of BABYLON.Scene to append to
  62620. * @param onSuccess a callback with the scene when import succeeds
  62621. * @param onProgress a callback with a progress event for each file being loaded
  62622. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  62623. * @param pluginExtension the extension used to determine the plugin
  62624. * @returns The loaded plugin
  62625. */
  62626. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  62627. if (onSuccess === void 0) { onSuccess = null; }
  62628. if (onProgress === void 0) { onProgress = null; }
  62629. if (onError === void 0) { onError = null; }
  62630. if (pluginExtension === void 0) { pluginExtension = null; }
  62631. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  62632. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  62633. return null;
  62634. }
  62635. if (SceneLoader.ShowLoadingScreen) {
  62636. scene.getEngine().displayLoadingUI();
  62637. }
  62638. var loadingToken = {};
  62639. scene._addPendingData(loadingToken);
  62640. var disposeHandler = function () {
  62641. scene._removePendingData(loadingToken);
  62642. scene.getEngine().hideLoadingUI();
  62643. };
  62644. var errorHandler = function (message, exception) {
  62645. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  62646. if (onError) {
  62647. onError(scene, errorMessage, exception);
  62648. }
  62649. else {
  62650. BABYLON.Tools.Error(errorMessage);
  62651. // should the exception be thrown?
  62652. }
  62653. disposeHandler();
  62654. };
  62655. var progressHandler = onProgress ? function (event) {
  62656. try {
  62657. onProgress(event);
  62658. }
  62659. catch (e) {
  62660. errorHandler("Error in onProgress callback", e);
  62661. }
  62662. } : undefined;
  62663. var successHandler = function () {
  62664. if (onSuccess) {
  62665. try {
  62666. onSuccess(scene);
  62667. }
  62668. catch (e) {
  62669. errorHandler("Error in onSuccess callback", e);
  62670. }
  62671. }
  62672. scene._removePendingData(loadingToken);
  62673. };
  62674. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  62675. if (sceneFilename === "") {
  62676. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  62677. }
  62678. if (plugin.load) {
  62679. var syncedPlugin = plugin;
  62680. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  62681. return;
  62682. }
  62683. scene.loadingPluginName = plugin.name;
  62684. successHandler();
  62685. }
  62686. else {
  62687. var asyncedPlugin = plugin;
  62688. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  62689. scene.loadingPluginName = plugin.name;
  62690. successHandler();
  62691. }).catch(function (error) {
  62692. errorHandler(error.message, error);
  62693. });
  62694. }
  62695. if (SceneLoader.ShowLoadingScreen) {
  62696. scene.executeWhenReady(function () {
  62697. scene.getEngine().hideLoadingUI();
  62698. });
  62699. }
  62700. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  62701. };
  62702. /**
  62703. * Append a scene
  62704. * @param rootUrl a string that defines the root url for scene and resources
  62705. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62706. * @param scene is the instance of BABYLON.Scene to append to
  62707. * @param onProgress a callback with a progress event for each file being loaded
  62708. * @param pluginExtension the extension used to determine the plugin
  62709. * @returns The given scene
  62710. */
  62711. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  62712. if (onProgress === void 0) { onProgress = null; }
  62713. if (pluginExtension === void 0) { pluginExtension = null; }
  62714. return new Promise(function (resolve, reject) {
  62715. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  62716. resolve(scene);
  62717. }, onProgress, function (scene, message, exception) {
  62718. reject(exception || new Error(message));
  62719. }, pluginExtension);
  62720. });
  62721. };
  62722. /**
  62723. * Load a scene into an asset container
  62724. * @param rootUrl a string that defines the root url for scene and resources
  62725. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62726. * @param scene is the instance of BABYLON.Scene to append to
  62727. * @param onSuccess a callback with the scene when import succeeds
  62728. * @param onProgress a callback with a progress event for each file being loaded
  62729. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  62730. * @param pluginExtension the extension used to determine the plugin
  62731. * @returns The loaded plugin
  62732. */
  62733. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  62734. if (onSuccess === void 0) { onSuccess = null; }
  62735. if (onProgress === void 0) { onProgress = null; }
  62736. if (onError === void 0) { onError = null; }
  62737. if (pluginExtension === void 0) { pluginExtension = null; }
  62738. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  62739. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  62740. return null;
  62741. }
  62742. var loadingToken = {};
  62743. scene._addPendingData(loadingToken);
  62744. var disposeHandler = function () {
  62745. scene._removePendingData(loadingToken);
  62746. };
  62747. var errorHandler = function (message, exception) {
  62748. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  62749. if (onError) {
  62750. onError(scene, errorMessage, exception);
  62751. }
  62752. else {
  62753. BABYLON.Tools.Error(errorMessage);
  62754. // should the exception be thrown?
  62755. }
  62756. disposeHandler();
  62757. };
  62758. var progressHandler = onProgress ? function (event) {
  62759. try {
  62760. onProgress(event);
  62761. }
  62762. catch (e) {
  62763. errorHandler("Error in onProgress callback", e);
  62764. }
  62765. } : undefined;
  62766. var successHandler = function (assets) {
  62767. if (onSuccess) {
  62768. try {
  62769. onSuccess(assets);
  62770. }
  62771. catch (e) {
  62772. errorHandler("Error in onSuccess callback", e);
  62773. }
  62774. }
  62775. scene._removePendingData(loadingToken);
  62776. };
  62777. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  62778. if (plugin.loadAssetContainer) {
  62779. var syncedPlugin = plugin;
  62780. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  62781. if (!assetContainer) {
  62782. return;
  62783. }
  62784. scene.loadingPluginName = plugin.name;
  62785. successHandler(assetContainer);
  62786. }
  62787. else if (plugin.loadAssetContainerAsync) {
  62788. var asyncedPlugin = plugin;
  62789. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  62790. scene.loadingPluginName = plugin.name;
  62791. successHandler(assetContainer);
  62792. }).catch(function (error) {
  62793. errorHandler(error.message, error);
  62794. });
  62795. }
  62796. else {
  62797. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  62798. }
  62799. if (SceneLoader.ShowLoadingScreen) {
  62800. scene.executeWhenReady(function () {
  62801. scene.getEngine().hideLoadingUI();
  62802. });
  62803. }
  62804. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  62805. };
  62806. /**
  62807. * Load a scene into an asset container
  62808. * @param rootUrl a string that defines the root url for scene and resources
  62809. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  62810. * @param scene is the instance of BABYLON.Scene to append to
  62811. * @param onProgress a callback with a progress event for each file being loaded
  62812. * @param pluginExtension the extension used to determine the plugin
  62813. * @returns The loaded asset container
  62814. */
  62815. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  62816. if (onProgress === void 0) { onProgress = null; }
  62817. if (pluginExtension === void 0) { pluginExtension = null; }
  62818. return new Promise(function (resolve, reject) {
  62819. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  62820. resolve(assetContainer);
  62821. }, onProgress, function (scene, message, exception) {
  62822. reject(exception || new Error(message));
  62823. }, pluginExtension);
  62824. });
  62825. };
  62826. // Flags
  62827. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  62828. SceneLoader._ShowLoadingScreen = true;
  62829. SceneLoader._CleanBoneMatrixWeights = false;
  62830. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  62831. // Members
  62832. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  62833. SceneLoader._registeredPlugins = {};
  62834. return SceneLoader;
  62835. }());
  62836. BABYLON.SceneLoader = SceneLoader;
  62837. ;
  62838. })(BABYLON || (BABYLON = {}));
  62839. //# sourceMappingURL=babylon.sceneLoader.js.map
  62840. "use strict";
  62841. var BABYLON;
  62842. (function (BABYLON) {
  62843. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  62844. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  62845. var parsedMaterial = parsedData.materials[index];
  62846. if (parsedMaterial.id === id) {
  62847. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  62848. }
  62849. }
  62850. return null;
  62851. };
  62852. var isDescendantOf = function (mesh, names, hierarchyIds) {
  62853. for (var i in names) {
  62854. if (mesh.name === names[i]) {
  62855. hierarchyIds.push(mesh.id);
  62856. return true;
  62857. }
  62858. }
  62859. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  62860. hierarchyIds.push(mesh.id);
  62861. return true;
  62862. }
  62863. return false;
  62864. };
  62865. var logOperation = function (operation, producer) {
  62866. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  62867. };
  62868. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  62869. if (addToScene === void 0) { addToScene = false; }
  62870. var container = new BABYLON.AssetContainer(scene);
  62871. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  62872. // when SceneLoader.debugLogging = true (default), or exception encountered.
  62873. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  62874. // and avoid problems with multiple concurrent .babylon loads.
  62875. var log = "importScene has failed JSON parse";
  62876. try {
  62877. var parsedData = JSON.parse(data);
  62878. log = "";
  62879. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  62880. var index;
  62881. var cache;
  62882. // Lights
  62883. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  62884. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  62885. var parsedLight = parsedData.lights[index];
  62886. var light = BABYLON.Light.Parse(parsedLight, scene);
  62887. if (light) {
  62888. container.lights.push(light);
  62889. log += (index === 0 ? "\n\tLights:" : "");
  62890. log += "\n\t\t" + light.toString(fullDetails);
  62891. }
  62892. }
  62893. }
  62894. // Animations
  62895. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  62896. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  62897. var parsedAnimation = parsedData.animations[index];
  62898. var animation = BABYLON.Animation.Parse(parsedAnimation);
  62899. scene.animations.push(animation);
  62900. container.animations.push(animation);
  62901. log += (index === 0 ? "\n\tAnimations:" : "");
  62902. log += "\n\t\t" + animation.toString(fullDetails);
  62903. }
  62904. }
  62905. // Materials
  62906. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  62907. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  62908. var parsedMaterial = parsedData.materials[index];
  62909. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  62910. container.materials.push(mat);
  62911. log += (index === 0 ? "\n\tMaterials:" : "");
  62912. log += "\n\t\t" + mat.toString(fullDetails);
  62913. }
  62914. }
  62915. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  62916. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  62917. var parsedMultiMaterial = parsedData.multiMaterials[index];
  62918. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  62919. container.multiMaterials.push(mmat);
  62920. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  62921. log += "\n\t\t" + mmat.toString(fullDetails);
  62922. }
  62923. }
  62924. // Morph targets
  62925. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  62926. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  62927. var managerData = _a[_i];
  62928. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  62929. }
  62930. }
  62931. // Skeletons
  62932. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  62933. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  62934. var parsedSkeleton = parsedData.skeletons[index];
  62935. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  62936. container.skeletons.push(skeleton);
  62937. log += (index === 0 ? "\n\tSkeletons:" : "");
  62938. log += "\n\t\t" + skeleton.toString(fullDetails);
  62939. }
  62940. }
  62941. // Geometries
  62942. var geometries = parsedData.geometries;
  62943. if (geometries !== undefined && geometries !== null) {
  62944. var addedGeometry = new Array();
  62945. // Boxes
  62946. var boxes = geometries.boxes;
  62947. if (boxes !== undefined && boxes !== null) {
  62948. for (index = 0, cache = boxes.length; index < cache; index++) {
  62949. var parsedBox = boxes[index];
  62950. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  62951. }
  62952. }
  62953. // Spheres
  62954. var spheres = geometries.spheres;
  62955. if (spheres !== undefined && spheres !== null) {
  62956. for (index = 0, cache = spheres.length; index < cache; index++) {
  62957. var parsedSphere = spheres[index];
  62958. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  62959. }
  62960. }
  62961. // Cylinders
  62962. var cylinders = geometries.cylinders;
  62963. if (cylinders !== undefined && cylinders !== null) {
  62964. for (index = 0, cache = cylinders.length; index < cache; index++) {
  62965. var parsedCylinder = cylinders[index];
  62966. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  62967. }
  62968. }
  62969. // Toruses
  62970. var toruses = geometries.toruses;
  62971. if (toruses !== undefined && toruses !== null) {
  62972. for (index = 0, cache = toruses.length; index < cache; index++) {
  62973. var parsedTorus = toruses[index];
  62974. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  62975. }
  62976. }
  62977. // Grounds
  62978. var grounds = geometries.grounds;
  62979. if (grounds !== undefined && grounds !== null) {
  62980. for (index = 0, cache = grounds.length; index < cache; index++) {
  62981. var parsedGround = grounds[index];
  62982. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  62983. }
  62984. }
  62985. // Planes
  62986. var planes = geometries.planes;
  62987. if (planes !== undefined && planes !== null) {
  62988. for (index = 0, cache = planes.length; index < cache; index++) {
  62989. var parsedPlane = planes[index];
  62990. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  62991. }
  62992. }
  62993. // TorusKnots
  62994. var torusKnots = geometries.torusKnots;
  62995. if (torusKnots !== undefined && torusKnots !== null) {
  62996. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  62997. var parsedTorusKnot = torusKnots[index];
  62998. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  62999. }
  63000. }
  63001. // VertexData
  63002. var vertexData = geometries.vertexData;
  63003. if (vertexData !== undefined && vertexData !== null) {
  63004. for (index = 0, cache = vertexData.length; index < cache; index++) {
  63005. var parsedVertexData = vertexData[index];
  63006. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  63007. }
  63008. }
  63009. addedGeometry.forEach(function (g) {
  63010. if (g) {
  63011. container.geometries.push(g);
  63012. }
  63013. });
  63014. }
  63015. // Transform nodes
  63016. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  63017. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  63018. var parsedTransformNode = parsedData.transformNodes[index];
  63019. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  63020. container.transformNodes.push(node);
  63021. }
  63022. }
  63023. // Meshes
  63024. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  63025. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  63026. var parsedMesh = parsedData.meshes[index];
  63027. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  63028. container.meshes.push(mesh);
  63029. log += (index === 0 ? "\n\tMeshes:" : "");
  63030. log += "\n\t\t" + mesh.toString(fullDetails);
  63031. }
  63032. }
  63033. // Cameras
  63034. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  63035. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  63036. var parsedCamera = parsedData.cameras[index];
  63037. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  63038. container.cameras.push(camera);
  63039. log += (index === 0 ? "\n\tCameras:" : "");
  63040. log += "\n\t\t" + camera.toString(fullDetails);
  63041. }
  63042. }
  63043. // Browsing all the graph to connect the dots
  63044. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  63045. var camera = scene.cameras[index];
  63046. if (camera._waitingParentId) {
  63047. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  63048. camera._waitingParentId = null;
  63049. }
  63050. }
  63051. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  63052. var light_1 = scene.lights[index];
  63053. if (light_1 && light_1._waitingParentId) {
  63054. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  63055. light_1._waitingParentId = null;
  63056. }
  63057. }
  63058. // Sounds
  63059. // TODO: add sound
  63060. var loadedSounds = [];
  63061. var loadedSound;
  63062. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  63063. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  63064. var parsedSound = parsedData.sounds[index];
  63065. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63066. if (!parsedSound.url)
  63067. parsedSound.url = parsedSound.name;
  63068. if (!loadedSounds[parsedSound.url]) {
  63069. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  63070. loadedSounds[parsedSound.url] = loadedSound;
  63071. container.sounds.push(loadedSound);
  63072. }
  63073. else {
  63074. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  63075. }
  63076. }
  63077. else {
  63078. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  63079. }
  63080. }
  63081. }
  63082. loadedSounds = [];
  63083. // Connect parents & children and parse actions
  63084. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  63085. var transformNode = scene.transformNodes[index];
  63086. if (transformNode._waitingParentId) {
  63087. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  63088. transformNode._waitingParentId = null;
  63089. }
  63090. }
  63091. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  63092. var mesh = scene.meshes[index];
  63093. if (mesh._waitingParentId) {
  63094. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  63095. mesh._waitingParentId = null;
  63096. }
  63097. if (mesh._waitingActions) {
  63098. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  63099. mesh._waitingActions = null;
  63100. }
  63101. }
  63102. // freeze world matrix application
  63103. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  63104. var currentMesh = scene.meshes[index];
  63105. if (currentMesh._waitingFreezeWorldMatrix) {
  63106. currentMesh.freezeWorldMatrix();
  63107. currentMesh._waitingFreezeWorldMatrix = null;
  63108. }
  63109. else {
  63110. currentMesh.computeWorldMatrix(true);
  63111. }
  63112. }
  63113. // Particles Systems
  63114. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  63115. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  63116. var parsedParticleSystem = parsedData.particleSystems[index];
  63117. if (parsedParticleSystem.activeParticleCount) {
  63118. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  63119. container.particleSystems.push(ps);
  63120. }
  63121. else {
  63122. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  63123. container.particleSystems.push(ps);
  63124. }
  63125. }
  63126. }
  63127. // Lens flares
  63128. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  63129. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  63130. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  63131. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  63132. container.lensFlareSystems.push(lf);
  63133. }
  63134. }
  63135. // Shadows
  63136. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  63137. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  63138. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  63139. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  63140. container.shadowGenerators.push(sg);
  63141. }
  63142. }
  63143. // Lights exclusions / inclusions
  63144. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  63145. var light_2 = scene.lights[index];
  63146. // Excluded check
  63147. if (light_2._excludedMeshesIds.length > 0) {
  63148. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  63149. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  63150. if (excludedMesh) {
  63151. light_2.excludedMeshes.push(excludedMesh);
  63152. }
  63153. }
  63154. light_2._excludedMeshesIds = [];
  63155. }
  63156. // Included check
  63157. if (light_2._includedOnlyMeshesIds.length > 0) {
  63158. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  63159. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  63160. if (includedOnlyMesh) {
  63161. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  63162. }
  63163. }
  63164. light_2._includedOnlyMeshesIds = [];
  63165. }
  63166. }
  63167. // Actions (scene)
  63168. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  63169. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  63170. }
  63171. if (!addToScene) {
  63172. container.removeAllFromScene();
  63173. }
  63174. }
  63175. catch (err) {
  63176. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  63177. if (onError) {
  63178. onError(msg, err);
  63179. }
  63180. else {
  63181. BABYLON.Tools.Log(msg);
  63182. throw err;
  63183. }
  63184. }
  63185. finally {
  63186. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  63187. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  63188. }
  63189. }
  63190. return container;
  63191. };
  63192. BABYLON.SceneLoader.RegisterPlugin({
  63193. name: "babylon.js",
  63194. extensions: ".babylon",
  63195. canDirectLoad: function (data) {
  63196. if (data.indexOf("babylon") !== -1) {
  63197. return true;
  63198. }
  63199. return false;
  63200. },
  63201. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  63202. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  63203. // when SceneLoader.debugLogging = true (default), or exception encountered.
  63204. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  63205. // and avoid problems with multiple concurrent .babylon loads.
  63206. var log = "importMesh has failed JSON parse";
  63207. try {
  63208. var parsedData = JSON.parse(data);
  63209. log = "";
  63210. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  63211. if (!meshesNames) {
  63212. meshesNames = null;
  63213. }
  63214. else if (!Array.isArray(meshesNames)) {
  63215. meshesNames = [meshesNames];
  63216. }
  63217. var hierarchyIds = new Array();
  63218. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  63219. var loadedSkeletonsIds = [];
  63220. var loadedMaterialsIds = [];
  63221. var index;
  63222. var cache;
  63223. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  63224. var parsedMesh = parsedData.meshes[index];
  63225. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  63226. if (meshesNames !== null) {
  63227. // Remove found mesh name from list.
  63228. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  63229. }
  63230. //Geometry?
  63231. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  63232. //does the file contain geometries?
  63233. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  63234. //find the correct geometry and add it to the scene
  63235. var found = false;
  63236. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  63237. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  63238. return;
  63239. }
  63240. else {
  63241. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  63242. if (parsedGeometryData.id === parsedMesh.geometryId) {
  63243. switch (geometryType) {
  63244. case "boxes":
  63245. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  63246. break;
  63247. case "spheres":
  63248. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  63249. break;
  63250. case "cylinders":
  63251. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  63252. break;
  63253. case "toruses":
  63254. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  63255. break;
  63256. case "grounds":
  63257. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  63258. break;
  63259. case "planes":
  63260. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  63261. break;
  63262. case "torusKnots":
  63263. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  63264. break;
  63265. case "vertexData":
  63266. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  63267. break;
  63268. }
  63269. found = true;
  63270. }
  63271. });
  63272. }
  63273. });
  63274. if (found === false) {
  63275. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  63276. }
  63277. }
  63278. }
  63279. // Material ?
  63280. if (parsedMesh.materialId) {
  63281. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  63282. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  63283. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  63284. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  63285. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  63286. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  63287. var subMatId = parsedMultiMaterial.materials[matIndex];
  63288. loadedMaterialsIds.push(subMatId);
  63289. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  63290. if (mat) {
  63291. log += "\n\tMaterial " + mat.toString(fullDetails);
  63292. }
  63293. }
  63294. loadedMaterialsIds.push(parsedMultiMaterial.id);
  63295. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  63296. if (mmat) {
  63297. materialFound = true;
  63298. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  63299. }
  63300. break;
  63301. }
  63302. }
  63303. }
  63304. if (materialFound === false) {
  63305. loadedMaterialsIds.push(parsedMesh.materialId);
  63306. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  63307. if (!mat) {
  63308. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  63309. }
  63310. else {
  63311. log += "\n\tMaterial " + mat.toString(fullDetails);
  63312. }
  63313. }
  63314. }
  63315. // Skeleton ?
  63316. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  63317. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  63318. if (skeletonAlreadyLoaded === false) {
  63319. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  63320. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  63321. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  63322. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  63323. skeletons.push(skeleton);
  63324. loadedSkeletonsIds.push(parsedSkeleton.id);
  63325. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  63326. }
  63327. }
  63328. }
  63329. }
  63330. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  63331. meshes.push(mesh);
  63332. log += "\n\tMesh " + mesh.toString(fullDetails);
  63333. }
  63334. }
  63335. // Connecting parents
  63336. var currentMesh;
  63337. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  63338. currentMesh = scene.meshes[index];
  63339. if (currentMesh._waitingParentId) {
  63340. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  63341. currentMesh._waitingParentId = null;
  63342. }
  63343. }
  63344. // freeze and compute world matrix application
  63345. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  63346. currentMesh = scene.meshes[index];
  63347. if (currentMesh._waitingFreezeWorldMatrix) {
  63348. currentMesh.freezeWorldMatrix();
  63349. currentMesh._waitingFreezeWorldMatrix = null;
  63350. }
  63351. else {
  63352. currentMesh.computeWorldMatrix(true);
  63353. }
  63354. }
  63355. }
  63356. // Particles
  63357. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  63358. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  63359. var parsedParticleSystem = parsedData.particleSystems[index];
  63360. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  63361. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  63362. }
  63363. }
  63364. }
  63365. return true;
  63366. }
  63367. catch (err) {
  63368. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  63369. if (onError) {
  63370. onError(msg, err);
  63371. }
  63372. else {
  63373. BABYLON.Tools.Log(msg);
  63374. throw err;
  63375. }
  63376. }
  63377. finally {
  63378. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  63379. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  63380. }
  63381. }
  63382. return false;
  63383. },
  63384. load: function (scene, data, rootUrl, onError) {
  63385. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  63386. // when SceneLoader.debugLogging = true (default), or exception encountered.
  63387. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  63388. // and avoid problems with multiple concurrent .babylon loads.
  63389. var log = "importScene has failed JSON parse";
  63390. try {
  63391. var parsedData = JSON.parse(data);
  63392. log = "";
  63393. // Scene
  63394. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  63395. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  63396. }
  63397. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  63398. scene.autoClear = parsedData.autoClear;
  63399. }
  63400. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  63401. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  63402. }
  63403. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  63404. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  63405. }
  63406. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  63407. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  63408. }
  63409. // Fog
  63410. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  63411. scene.fogMode = parsedData.fogMode;
  63412. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  63413. scene.fogStart = parsedData.fogStart;
  63414. scene.fogEnd = parsedData.fogEnd;
  63415. scene.fogDensity = parsedData.fogDensity;
  63416. log += "\tFog mode for scene: ";
  63417. switch (scene.fogMode) {
  63418. // getters not compiling, so using hardcoded
  63419. case 1:
  63420. log += "exp\n";
  63421. break;
  63422. case 2:
  63423. log += "exp2\n";
  63424. break;
  63425. case 3:
  63426. log += "linear\n";
  63427. break;
  63428. }
  63429. }
  63430. //Physics
  63431. if (parsedData.physicsEnabled) {
  63432. var physicsPlugin;
  63433. if (parsedData.physicsEngine === "cannon") {
  63434. physicsPlugin = new BABYLON.CannonJSPlugin();
  63435. }
  63436. else if (parsedData.physicsEngine === "oimo") {
  63437. physicsPlugin = new BABYLON.OimoJSPlugin();
  63438. }
  63439. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  63440. //else - default engine, which is currently oimo
  63441. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  63442. scene.enablePhysics(physicsGravity, physicsPlugin);
  63443. }
  63444. // Metadata
  63445. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  63446. scene.metadata = parsedData.metadata;
  63447. }
  63448. //collisions, if defined. otherwise, default is true
  63449. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  63450. scene.collisionsEnabled = parsedData.collisionsEnabled;
  63451. }
  63452. scene.workerCollisions = !!parsedData.workerCollisions;
  63453. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  63454. if (!container) {
  63455. return false;
  63456. }
  63457. if (parsedData.autoAnimate) {
  63458. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  63459. }
  63460. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  63461. scene.setActiveCameraByID(parsedData.activeCameraID);
  63462. }
  63463. // Environment texture
  63464. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  63465. scene.environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  63466. if (parsedData.createDefaultSkybox === true) {
  63467. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  63468. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  63469. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  63470. }
  63471. }
  63472. // Finish
  63473. return true;
  63474. }
  63475. catch (err) {
  63476. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  63477. if (onError) {
  63478. onError(msg, err);
  63479. }
  63480. else {
  63481. BABYLON.Tools.Log(msg);
  63482. throw err;
  63483. }
  63484. }
  63485. finally {
  63486. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  63487. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  63488. }
  63489. }
  63490. return false;
  63491. },
  63492. loadAssetContainer: function (scene, data, rootUrl, onError) {
  63493. var container = loadAssetContainer(scene, data, rootUrl, onError);
  63494. return container;
  63495. }
  63496. });
  63497. })(BABYLON || (BABYLON = {}));
  63498. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  63499. "use strict";
  63500. var BABYLON;
  63501. (function (BABYLON) {
  63502. var FilesInput = /** @class */ (function () {
  63503. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  63504. this.onProcessFileCallback = function () { return true; };
  63505. this._engine = engine;
  63506. this._currentScene = scene;
  63507. this._sceneLoadedCallback = sceneLoadedCallback;
  63508. this._progressCallback = progressCallback;
  63509. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  63510. this._textureLoadingCallback = textureLoadingCallback;
  63511. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  63512. this._onReloadCallback = onReloadCallback;
  63513. this._errorCallback = errorCallback;
  63514. }
  63515. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  63516. var _this = this;
  63517. if (elementToMonitor) {
  63518. this._elementToMonitor = elementToMonitor;
  63519. this._dragEnterHandler = function (e) { _this.drag(e); };
  63520. this._dragOverHandler = function (e) { _this.drag(e); };
  63521. this._dropHandler = function (e) { _this.drop(e); };
  63522. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  63523. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  63524. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  63525. }
  63526. };
  63527. FilesInput.prototype.dispose = function () {
  63528. if (!this._elementToMonitor) {
  63529. return;
  63530. }
  63531. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  63532. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  63533. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  63534. };
  63535. FilesInput.prototype.renderFunction = function () {
  63536. if (this._additionalRenderLoopLogicCallback) {
  63537. this._additionalRenderLoopLogicCallback();
  63538. }
  63539. if (this._currentScene) {
  63540. if (this._textureLoadingCallback) {
  63541. var remaining = this._currentScene.getWaitingItemsCount();
  63542. if (remaining > 0) {
  63543. this._textureLoadingCallback(remaining);
  63544. }
  63545. }
  63546. this._currentScene.render();
  63547. }
  63548. };
  63549. FilesInput.prototype.drag = function (e) {
  63550. e.stopPropagation();
  63551. e.preventDefault();
  63552. };
  63553. FilesInput.prototype.drop = function (eventDrop) {
  63554. eventDrop.stopPropagation();
  63555. eventDrop.preventDefault();
  63556. this.loadFiles(eventDrop);
  63557. };
  63558. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  63559. var _this = this;
  63560. var reader = folder.createReader();
  63561. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  63562. reader.readEntries(function (entries) {
  63563. remaining.count += entries.length;
  63564. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  63565. var entry = entries_1[_i];
  63566. if (entry.isFile) {
  63567. entry.file(function (file) {
  63568. file.correctName = relativePath + file.name;
  63569. files.push(file);
  63570. if (--remaining.count === 0) {
  63571. callback();
  63572. }
  63573. });
  63574. }
  63575. else if (entry.isDirectory) {
  63576. _this._traverseFolder(entry, files, remaining, callback);
  63577. }
  63578. }
  63579. if (--remaining.count) {
  63580. callback();
  63581. }
  63582. });
  63583. };
  63584. FilesInput.prototype._processFiles = function (files) {
  63585. for (var i = 0; i < files.length; i++) {
  63586. var name = files[i].correctName.toLowerCase();
  63587. var extension = name.split('.').pop();
  63588. if (!this.onProcessFileCallback(files[i], name, extension)) {
  63589. continue;
  63590. }
  63591. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  63592. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  63593. this._sceneFileToLoad = files[i];
  63594. }
  63595. else {
  63596. FilesInput.FilesToLoad[name] = files[i];
  63597. }
  63598. }
  63599. };
  63600. FilesInput.prototype.loadFiles = function (event) {
  63601. var _this = this;
  63602. if (this._startingProcessingFilesCallback)
  63603. this._startingProcessingFilesCallback();
  63604. // Handling data transfer via drag'n'drop
  63605. if (event && event.dataTransfer && event.dataTransfer.files) {
  63606. this._filesToLoad = event.dataTransfer.files;
  63607. }
  63608. // Handling files from input files
  63609. if (event && event.target && event.target.files) {
  63610. this._filesToLoad = event.target.files;
  63611. }
  63612. if (this._filesToLoad && this._filesToLoad.length > 0) {
  63613. var files_1 = new Array();
  63614. var folders = [];
  63615. var items = event.dataTransfer ? event.dataTransfer.items : null;
  63616. for (var i = 0; i < this._filesToLoad.length; i++) {
  63617. var fileToLoad = this._filesToLoad[i];
  63618. var name_1 = fileToLoad.name.toLowerCase();
  63619. var entry = void 0;
  63620. fileToLoad.correctName = name_1;
  63621. if (items) {
  63622. var item = items[i];
  63623. if (item.getAsEntry) {
  63624. entry = item.getAsEntry();
  63625. }
  63626. else if (item.webkitGetAsEntry) {
  63627. entry = item.webkitGetAsEntry();
  63628. }
  63629. }
  63630. if (!entry) {
  63631. files_1.push(fileToLoad);
  63632. }
  63633. else {
  63634. if (entry.isDirectory) {
  63635. folders.push(entry);
  63636. }
  63637. else {
  63638. files_1.push(fileToLoad);
  63639. }
  63640. }
  63641. }
  63642. if (folders.length === 0) {
  63643. this._processFiles(files_1);
  63644. this._processReload();
  63645. }
  63646. else {
  63647. var remaining = { count: folders.length };
  63648. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  63649. var folder = folders_1[_i];
  63650. this._traverseFolder(folder, files_1, remaining, function () {
  63651. _this._processFiles(files_1);
  63652. if (remaining.count === 0) {
  63653. _this._processReload();
  63654. }
  63655. });
  63656. }
  63657. }
  63658. }
  63659. };
  63660. FilesInput.prototype._processReload = function () {
  63661. if (this._onReloadCallback) {
  63662. this._onReloadCallback(this._sceneFileToLoad);
  63663. }
  63664. else {
  63665. this.reload();
  63666. }
  63667. };
  63668. FilesInput.prototype.reload = function () {
  63669. var _this = this;
  63670. // If a scene file has been provided
  63671. if (this._sceneFileToLoad) {
  63672. if (this._currentScene) {
  63673. if (BABYLON.Tools.errorsCount > 0) {
  63674. BABYLON.Tools.ClearLogCache();
  63675. }
  63676. this._engine.stopRenderLoop();
  63677. this._currentScene.dispose();
  63678. }
  63679. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  63680. if (_this._progressCallback) {
  63681. _this._progressCallback(progress);
  63682. }
  63683. }).then(function (scene) {
  63684. _this._currentScene = scene;
  63685. if (_this._sceneLoadedCallback) {
  63686. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  63687. }
  63688. // Wait for textures and shaders to be ready
  63689. _this._currentScene.executeWhenReady(function () {
  63690. _this._engine.runRenderLoop(function () {
  63691. _this.renderFunction();
  63692. });
  63693. });
  63694. }).catch(function (error) {
  63695. if (_this._errorCallback) {
  63696. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  63697. }
  63698. });
  63699. }
  63700. else {
  63701. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  63702. }
  63703. };
  63704. FilesInput.FilesToLoad = {};
  63705. return FilesInput;
  63706. }());
  63707. BABYLON.FilesInput = FilesInput;
  63708. })(BABYLON || (BABYLON = {}));
  63709. //# sourceMappingURL=babylon.filesInput.js.map
  63710. "use strict";
  63711. var BABYLON;
  63712. (function (BABYLON) {
  63713. /**
  63714. * This class implement a typical dictionary using a string as key and the generic type T as value.
  63715. * The underlying implementation relies on an associative array to ensure the best performances.
  63716. * The value can be anything including 'null' but except 'undefined'
  63717. */
  63718. var StringDictionary = /** @class */ (function () {
  63719. function StringDictionary() {
  63720. this._count = 0;
  63721. this._data = {};
  63722. }
  63723. /**
  63724. * This will clear this dictionary and copy the content from the 'source' one.
  63725. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  63726. * @param source the dictionary to take the content from and copy to this dictionary
  63727. */
  63728. StringDictionary.prototype.copyFrom = function (source) {
  63729. var _this = this;
  63730. this.clear();
  63731. source.forEach(function (t, v) { return _this.add(t, v); });
  63732. };
  63733. /**
  63734. * Get a value based from its key
  63735. * @param key the given key to get the matching value from
  63736. * @return the value if found, otherwise undefined is returned
  63737. */
  63738. StringDictionary.prototype.get = function (key) {
  63739. var val = this._data[key];
  63740. if (val !== undefined) {
  63741. return val;
  63742. }
  63743. return undefined;
  63744. };
  63745. /**
  63746. * Get a value from its key or add it if it doesn't exist.
  63747. * This method will ensure you that a given key/data will be present in the dictionary.
  63748. * @param key the given key to get the matching value from
  63749. * @param factory the factory that will create the value if the key is not present in the dictionary.
  63750. * The factory will only be invoked if there's no data for the given key.
  63751. * @return the value corresponding to the key.
  63752. */
  63753. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  63754. var val = this.get(key);
  63755. if (val !== undefined) {
  63756. return val;
  63757. }
  63758. val = factory(key);
  63759. if (val) {
  63760. this.add(key, val);
  63761. }
  63762. return val;
  63763. };
  63764. /**
  63765. * Get a value from its key if present in the dictionary otherwise add it
  63766. * @param key the key to get the value from
  63767. * @param val if there's no such key/value pair in the dictionary add it with this value
  63768. * @return the value corresponding to the key
  63769. */
  63770. StringDictionary.prototype.getOrAdd = function (key, val) {
  63771. var curVal = this.get(key);
  63772. if (curVal !== undefined) {
  63773. return curVal;
  63774. }
  63775. this.add(key, val);
  63776. return val;
  63777. };
  63778. /**
  63779. * Check if there's a given key in the dictionary
  63780. * @param key the key to check for
  63781. * @return true if the key is present, false otherwise
  63782. */
  63783. StringDictionary.prototype.contains = function (key) {
  63784. return this._data[key] !== undefined;
  63785. };
  63786. /**
  63787. * Add a new key and its corresponding value
  63788. * @param key the key to add
  63789. * @param value the value corresponding to the key
  63790. * @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
  63791. */
  63792. StringDictionary.prototype.add = function (key, value) {
  63793. if (this._data[key] !== undefined) {
  63794. return false;
  63795. }
  63796. this._data[key] = value;
  63797. ++this._count;
  63798. return true;
  63799. };
  63800. StringDictionary.prototype.set = function (key, value) {
  63801. if (this._data[key] === undefined) {
  63802. return false;
  63803. }
  63804. this._data[key] = value;
  63805. return true;
  63806. };
  63807. /**
  63808. * Get the element of the given key and remove it from the dictionary
  63809. * @param key
  63810. */
  63811. StringDictionary.prototype.getAndRemove = function (key) {
  63812. var val = this.get(key);
  63813. if (val !== undefined) {
  63814. delete this._data[key];
  63815. --this._count;
  63816. return val;
  63817. }
  63818. return null;
  63819. };
  63820. /**
  63821. * Remove a key/value from the dictionary.
  63822. * @param key the key to remove
  63823. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  63824. */
  63825. StringDictionary.prototype.remove = function (key) {
  63826. if (this.contains(key)) {
  63827. delete this._data[key];
  63828. --this._count;
  63829. return true;
  63830. }
  63831. return false;
  63832. };
  63833. /**
  63834. * Clear the whole content of the dictionary
  63835. */
  63836. StringDictionary.prototype.clear = function () {
  63837. this._data = {};
  63838. this._count = 0;
  63839. };
  63840. Object.defineProperty(StringDictionary.prototype, "count", {
  63841. get: function () {
  63842. return this._count;
  63843. },
  63844. enumerable: true,
  63845. configurable: true
  63846. });
  63847. /**
  63848. * Execute a callback on each key/val of the dictionary.
  63849. * Note that you can remove any element in this dictionary in the callback implementation
  63850. * @param callback the callback to execute on a given key/value pair
  63851. */
  63852. StringDictionary.prototype.forEach = function (callback) {
  63853. for (var cur in this._data) {
  63854. var val = this._data[cur];
  63855. callback(cur, val);
  63856. }
  63857. };
  63858. /**
  63859. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  63860. * If the callback returns null or undefined the method will iterate to the next key/value pair
  63861. * Note that you can remove any element in this dictionary in the callback implementation
  63862. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  63863. */
  63864. StringDictionary.prototype.first = function (callback) {
  63865. for (var cur in this._data) {
  63866. var val = this._data[cur];
  63867. var res = callback(cur, val);
  63868. if (res) {
  63869. return res;
  63870. }
  63871. }
  63872. return null;
  63873. };
  63874. return StringDictionary;
  63875. }());
  63876. BABYLON.StringDictionary = StringDictionary;
  63877. })(BABYLON || (BABYLON = {}));
  63878. //# sourceMappingURL=babylon.stringDictionary.js.map
  63879. "use strict";
  63880. var BABYLON;
  63881. (function (BABYLON) {
  63882. var Tags = /** @class */ (function () {
  63883. function Tags() {
  63884. }
  63885. Tags.EnableFor = function (obj) {
  63886. obj._tags = obj._tags || {};
  63887. obj.hasTags = function () {
  63888. return Tags.HasTags(obj);
  63889. };
  63890. obj.addTags = function (tagsString) {
  63891. return Tags.AddTagsTo(obj, tagsString);
  63892. };
  63893. obj.removeTags = function (tagsString) {
  63894. return Tags.RemoveTagsFrom(obj, tagsString);
  63895. };
  63896. obj.matchesTagsQuery = function (tagsQuery) {
  63897. return Tags.MatchesQuery(obj, tagsQuery);
  63898. };
  63899. };
  63900. Tags.DisableFor = function (obj) {
  63901. delete obj._tags;
  63902. delete obj.hasTags;
  63903. delete obj.addTags;
  63904. delete obj.removeTags;
  63905. delete obj.matchesTagsQuery;
  63906. };
  63907. Tags.HasTags = function (obj) {
  63908. if (!obj._tags) {
  63909. return false;
  63910. }
  63911. return !BABYLON.Tools.IsEmpty(obj._tags);
  63912. };
  63913. Tags.GetTags = function (obj, asString) {
  63914. if (asString === void 0) { asString = true; }
  63915. if (!obj._tags) {
  63916. return null;
  63917. }
  63918. if (asString) {
  63919. var tagsArray = [];
  63920. for (var tag in obj._tags) {
  63921. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  63922. tagsArray.push(tag);
  63923. }
  63924. }
  63925. return tagsArray.join(" ");
  63926. }
  63927. else {
  63928. return obj._tags;
  63929. }
  63930. };
  63931. // the tags 'true' and 'false' are reserved and cannot be used as tags
  63932. // a tag cannot start with '||', '&&', and '!'
  63933. // it cannot contain whitespaces
  63934. Tags.AddTagsTo = function (obj, tagsString) {
  63935. if (!tagsString) {
  63936. return;
  63937. }
  63938. if (typeof tagsString !== "string") {
  63939. return;
  63940. }
  63941. var tags = tagsString.split(" ");
  63942. tags.forEach(function (tag, index, array) {
  63943. Tags._AddTagTo(obj, tag);
  63944. });
  63945. };
  63946. Tags._AddTagTo = function (obj, tag) {
  63947. tag = tag.trim();
  63948. if (tag === "" || tag === "true" || tag === "false") {
  63949. return;
  63950. }
  63951. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  63952. return;
  63953. }
  63954. Tags.EnableFor(obj);
  63955. obj._tags[tag] = true;
  63956. };
  63957. Tags.RemoveTagsFrom = function (obj, tagsString) {
  63958. if (!Tags.HasTags(obj)) {
  63959. return;
  63960. }
  63961. var tags = tagsString.split(" ");
  63962. for (var t in tags) {
  63963. Tags._RemoveTagFrom(obj, tags[t]);
  63964. }
  63965. };
  63966. Tags._RemoveTagFrom = function (obj, tag) {
  63967. delete obj._tags[tag];
  63968. };
  63969. Tags.MatchesQuery = function (obj, tagsQuery) {
  63970. if (tagsQuery === undefined) {
  63971. return true;
  63972. }
  63973. if (tagsQuery === "") {
  63974. return Tags.HasTags(obj);
  63975. }
  63976. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  63977. };
  63978. return Tags;
  63979. }());
  63980. BABYLON.Tags = Tags;
  63981. })(BABYLON || (BABYLON = {}));
  63982. //# sourceMappingURL=babylon.tags.js.map
  63983. "use strict";
  63984. var BABYLON;
  63985. (function (BABYLON) {
  63986. var AndOrNotEvaluator = /** @class */ (function () {
  63987. function AndOrNotEvaluator() {
  63988. }
  63989. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  63990. if (!query.match(/\([^\(\)]*\)/g)) {
  63991. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  63992. }
  63993. else {
  63994. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  63995. // remove parenthesis
  63996. r = r.slice(1, r.length - 1);
  63997. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  63998. });
  63999. }
  64000. if (query === "true") {
  64001. return true;
  64002. }
  64003. if (query === "false") {
  64004. return false;
  64005. }
  64006. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  64007. };
  64008. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  64009. evaluateCallback = evaluateCallback || (function (r) {
  64010. return r === "true" ? true : false;
  64011. });
  64012. var result;
  64013. var or = parenthesisContent.split("||");
  64014. for (var i in or) {
  64015. if (or.hasOwnProperty(i)) {
  64016. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  64017. var and = ori.split("&&");
  64018. if (and.length > 1) {
  64019. for (var j = 0; j < and.length; ++j) {
  64020. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  64021. if (andj !== "true" && andj !== "false") {
  64022. if (andj[0] === "!") {
  64023. result = !evaluateCallback(andj.substring(1));
  64024. }
  64025. else {
  64026. result = evaluateCallback(andj);
  64027. }
  64028. }
  64029. else {
  64030. result = andj === "true" ? true : false;
  64031. }
  64032. if (!result) {
  64033. ori = "false";
  64034. break;
  64035. }
  64036. }
  64037. }
  64038. if (result || ori === "true") {
  64039. result = true;
  64040. break;
  64041. }
  64042. // result equals false (or undefined)
  64043. if (ori !== "true" && ori !== "false") {
  64044. if (ori[0] === "!") {
  64045. result = !evaluateCallback(ori.substring(1));
  64046. }
  64047. else {
  64048. result = evaluateCallback(ori);
  64049. }
  64050. }
  64051. else {
  64052. result = ori === "true" ? true : false;
  64053. }
  64054. }
  64055. }
  64056. // the whole parenthesis scope is replaced by 'true' or 'false'
  64057. return result ? "true" : "false";
  64058. };
  64059. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  64060. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  64061. // remove whitespaces
  64062. r = r.replace(/[\s]/g, function () { return ""; });
  64063. return r.length % 2 ? "!" : "";
  64064. });
  64065. booleanString = booleanString.trim();
  64066. if (booleanString === "!true") {
  64067. booleanString = "false";
  64068. }
  64069. else if (booleanString === "!false") {
  64070. booleanString = "true";
  64071. }
  64072. return booleanString;
  64073. };
  64074. return AndOrNotEvaluator;
  64075. }());
  64076. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  64077. })(BABYLON || (BABYLON = {}));
  64078. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  64079. "use strict";
  64080. var BABYLON;
  64081. (function (BABYLON) {
  64082. var Database = /** @class */ (function () {
  64083. function Database(urlToScene, callbackManifestChecked) {
  64084. // Handling various flavors of prefixed version of IndexedDB
  64085. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  64086. this.callbackManifestChecked = callbackManifestChecked;
  64087. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  64088. this.db = null;
  64089. this._enableSceneOffline = false;
  64090. this._enableTexturesOffline = false;
  64091. this.manifestVersionFound = 0;
  64092. this.mustUpdateRessources = false;
  64093. this.hasReachedQuota = false;
  64094. if (!Database.IDBStorageEnabled) {
  64095. this.callbackManifestChecked(true);
  64096. }
  64097. else {
  64098. this.checkManifestFile();
  64099. }
  64100. }
  64101. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  64102. get: function () {
  64103. return this._enableSceneOffline;
  64104. },
  64105. enumerable: true,
  64106. configurable: true
  64107. });
  64108. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  64109. get: function () {
  64110. return this._enableTexturesOffline;
  64111. },
  64112. enumerable: true,
  64113. configurable: true
  64114. });
  64115. Database.prototype.checkManifestFile = function () {
  64116. var _this = this;
  64117. var noManifestFile = function () {
  64118. _this._enableSceneOffline = false;
  64119. _this._enableTexturesOffline = false;
  64120. _this.callbackManifestChecked(false);
  64121. };
  64122. var timeStampUsed = false;
  64123. var manifestURL = this.currentSceneUrl + ".manifest";
  64124. var xhr = new XMLHttpRequest();
  64125. if (navigator.onLine) {
  64126. // Adding a timestamp to by-pass browsers' cache
  64127. timeStampUsed = true;
  64128. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  64129. }
  64130. xhr.open("GET", manifestURL, true);
  64131. xhr.addEventListener("load", function () {
  64132. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  64133. try {
  64134. var manifestFile = JSON.parse(xhr.response);
  64135. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  64136. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  64137. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  64138. _this.manifestVersionFound = manifestFile.version;
  64139. }
  64140. if (_this.callbackManifestChecked) {
  64141. _this.callbackManifestChecked(true);
  64142. }
  64143. }
  64144. catch (ex) {
  64145. noManifestFile();
  64146. }
  64147. }
  64148. else {
  64149. noManifestFile();
  64150. }
  64151. }, false);
  64152. xhr.addEventListener("error", function (event) {
  64153. if (timeStampUsed) {
  64154. timeStampUsed = false;
  64155. // Let's retry without the timeStamp
  64156. // It could fail when coupled with HTML5 Offline API
  64157. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  64158. xhr.open("GET", retryManifestURL, true);
  64159. xhr.send();
  64160. }
  64161. else {
  64162. noManifestFile();
  64163. }
  64164. }, false);
  64165. try {
  64166. xhr.send();
  64167. }
  64168. catch (ex) {
  64169. BABYLON.Tools.Error("Error on XHR send request.");
  64170. this.callbackManifestChecked(false);
  64171. }
  64172. };
  64173. Database.prototype.openAsync = function (successCallback, errorCallback) {
  64174. var _this = this;
  64175. var handleError = function () {
  64176. _this.isSupported = false;
  64177. if (errorCallback)
  64178. errorCallback();
  64179. };
  64180. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  64181. // Your browser doesn't support IndexedDB
  64182. this.isSupported = false;
  64183. if (errorCallback)
  64184. errorCallback();
  64185. }
  64186. else {
  64187. // If the DB hasn't been opened or created yet
  64188. if (!this.db) {
  64189. this.hasReachedQuota = false;
  64190. this.isSupported = true;
  64191. var request = this.idbFactory.open("babylonjs", 1);
  64192. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  64193. request.onerror = function (event) {
  64194. handleError();
  64195. };
  64196. // executes when a version change transaction cannot complete due to other active transactions
  64197. request.onblocked = function (event) {
  64198. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  64199. handleError();
  64200. };
  64201. // DB has been opened successfully
  64202. request.onsuccess = function (event) {
  64203. _this.db = request.result;
  64204. successCallback();
  64205. };
  64206. // Initialization of the DB. Creating Scenes & Textures stores
  64207. request.onupgradeneeded = function (event) {
  64208. _this.db = (event.target).result;
  64209. if (_this.db) {
  64210. try {
  64211. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  64212. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  64213. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  64214. }
  64215. catch (ex) {
  64216. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  64217. handleError();
  64218. }
  64219. }
  64220. };
  64221. }
  64222. else {
  64223. if (successCallback)
  64224. successCallback();
  64225. }
  64226. }
  64227. };
  64228. Database.prototype.loadImageFromDB = function (url, image) {
  64229. var _this = this;
  64230. var completeURL = Database.ReturnFullUrlLocation(url);
  64231. var saveAndLoadImage = function () {
  64232. if (!_this.hasReachedQuota && _this.db !== null) {
  64233. // the texture is not yet in the DB, let's try to save it
  64234. _this._saveImageIntoDBAsync(completeURL, image);
  64235. }
  64236. else {
  64237. image.src = url;
  64238. }
  64239. };
  64240. if (!this.mustUpdateRessources) {
  64241. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  64242. }
  64243. else {
  64244. saveAndLoadImage();
  64245. }
  64246. };
  64247. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  64248. if (this.isSupported && this.db !== null) {
  64249. var texture;
  64250. var transaction = this.db.transaction(["textures"]);
  64251. transaction.onabort = function (event) {
  64252. image.src = url;
  64253. };
  64254. transaction.oncomplete = function (event) {
  64255. var blobTextureURL;
  64256. if (texture) {
  64257. var URL = window.URL || window.webkitURL;
  64258. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  64259. image.onerror = function () {
  64260. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  64261. image.src = url;
  64262. };
  64263. image.src = blobTextureURL;
  64264. }
  64265. else {
  64266. notInDBCallback();
  64267. }
  64268. };
  64269. var getRequest = transaction.objectStore("textures").get(url);
  64270. getRequest.onsuccess = function (event) {
  64271. texture = (event.target).result;
  64272. };
  64273. getRequest.onerror = function (event) {
  64274. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  64275. image.src = url;
  64276. };
  64277. }
  64278. else {
  64279. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64280. image.src = url;
  64281. }
  64282. };
  64283. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  64284. var _this = this;
  64285. if (this.isSupported) {
  64286. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  64287. var generateBlobUrl = function () {
  64288. var blobTextureURL;
  64289. if (blob) {
  64290. var URL = window.URL || window.webkitURL;
  64291. try {
  64292. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  64293. }
  64294. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  64295. catch (ex) {
  64296. blobTextureURL = URL.createObjectURL(blob);
  64297. }
  64298. }
  64299. if (blobTextureURL) {
  64300. image.src = blobTextureURL;
  64301. }
  64302. };
  64303. if (Database.IsUASupportingBlobStorage) {
  64304. var xhr = new XMLHttpRequest(), blob;
  64305. xhr.open("GET", url, true);
  64306. xhr.responseType = "blob";
  64307. xhr.addEventListener("load", function () {
  64308. if (xhr.status === 200 && _this.db) {
  64309. // Blob as response (XHR2)
  64310. blob = xhr.response;
  64311. var transaction = _this.db.transaction(["textures"], "readwrite");
  64312. // the transaction could abort because of a QuotaExceededError error
  64313. transaction.onabort = function (event) {
  64314. try {
  64315. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  64316. var srcElement = (event.srcElement || event.target);
  64317. var error = srcElement.error;
  64318. if (error && error.name === "QuotaExceededError") {
  64319. _this.hasReachedQuota = true;
  64320. }
  64321. }
  64322. catch (ex) { }
  64323. generateBlobUrl();
  64324. };
  64325. transaction.oncomplete = function (event) {
  64326. generateBlobUrl();
  64327. };
  64328. var newTexture = { textureUrl: url, data: blob };
  64329. try {
  64330. // Put the blob into the dabase
  64331. var addRequest = transaction.objectStore("textures").put(newTexture);
  64332. addRequest.onsuccess = function (event) {
  64333. };
  64334. addRequest.onerror = function (event) {
  64335. generateBlobUrl();
  64336. };
  64337. }
  64338. catch (ex) {
  64339. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  64340. if (ex.code === 25) {
  64341. Database.IsUASupportingBlobStorage = false;
  64342. }
  64343. image.src = url;
  64344. }
  64345. }
  64346. else {
  64347. image.src = url;
  64348. }
  64349. }, false);
  64350. xhr.addEventListener("error", function (event) {
  64351. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  64352. image.src = url;
  64353. }, false);
  64354. xhr.send();
  64355. }
  64356. else {
  64357. image.src = url;
  64358. }
  64359. }
  64360. else {
  64361. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64362. image.src = url;
  64363. }
  64364. };
  64365. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  64366. var _this = this;
  64367. var updateVersion = function () {
  64368. // the version is not yet in the DB or we need to update it
  64369. _this._saveVersionIntoDBAsync(url, versionLoaded);
  64370. };
  64371. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  64372. };
  64373. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  64374. var _this = this;
  64375. if (this.isSupported && this.db) {
  64376. var version;
  64377. try {
  64378. var transaction = this.db.transaction(["versions"]);
  64379. transaction.oncomplete = function (event) {
  64380. if (version) {
  64381. // If the version in the JSON file is > than the version in DB
  64382. if (_this.manifestVersionFound > version.data) {
  64383. _this.mustUpdateRessources = true;
  64384. updateInDBCallback();
  64385. }
  64386. else {
  64387. callback(version.data);
  64388. }
  64389. }
  64390. else {
  64391. _this.mustUpdateRessources = true;
  64392. updateInDBCallback();
  64393. }
  64394. };
  64395. transaction.onabort = function (event) {
  64396. callback(-1);
  64397. };
  64398. var getRequest = transaction.objectStore("versions").get(url);
  64399. getRequest.onsuccess = function (event) {
  64400. version = (event.target).result;
  64401. };
  64402. getRequest.onerror = function (event) {
  64403. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  64404. callback(-1);
  64405. };
  64406. }
  64407. catch (ex) {
  64408. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  64409. callback(-1);
  64410. }
  64411. }
  64412. else {
  64413. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64414. callback(-1);
  64415. }
  64416. };
  64417. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  64418. var _this = this;
  64419. if (this.isSupported && !this.hasReachedQuota && this.db) {
  64420. try {
  64421. // Open a transaction to the database
  64422. var transaction = this.db.transaction(["versions"], "readwrite");
  64423. // the transaction could abort because of a QuotaExceededError error
  64424. transaction.onabort = function (event) {
  64425. try {
  64426. var error = event.srcElement['error'];
  64427. if (error && error.name === "QuotaExceededError") {
  64428. _this.hasReachedQuota = true;
  64429. }
  64430. }
  64431. catch (ex) { }
  64432. callback(-1);
  64433. };
  64434. transaction.oncomplete = function (event) {
  64435. callback(_this.manifestVersionFound);
  64436. };
  64437. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  64438. // Put the scene into the database
  64439. var addRequest = transaction.objectStore("versions").put(newVersion);
  64440. addRequest.onsuccess = function (event) {
  64441. };
  64442. addRequest.onerror = function (event) {
  64443. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  64444. };
  64445. }
  64446. catch (ex) {
  64447. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  64448. callback(-1);
  64449. }
  64450. }
  64451. else {
  64452. callback(-1);
  64453. }
  64454. };
  64455. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  64456. var _this = this;
  64457. var completeUrl = Database.ReturnFullUrlLocation(url);
  64458. var saveAndLoadFile = function () {
  64459. // the scene is not yet in the DB, let's try to save it
  64460. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  64461. };
  64462. this._checkVersionFromDB(completeUrl, function (version) {
  64463. if (version !== -1) {
  64464. if (!_this.mustUpdateRessources) {
  64465. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  64466. }
  64467. else {
  64468. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  64469. }
  64470. }
  64471. else {
  64472. if (errorCallback) {
  64473. errorCallback();
  64474. }
  64475. }
  64476. });
  64477. };
  64478. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  64479. if (this.isSupported && this.db) {
  64480. var targetStore;
  64481. if (url.indexOf(".babylon") !== -1) {
  64482. targetStore = "scenes";
  64483. }
  64484. else {
  64485. targetStore = "textures";
  64486. }
  64487. var file;
  64488. var transaction = this.db.transaction([targetStore]);
  64489. transaction.oncomplete = function (event) {
  64490. if (file) {
  64491. callback(file.data);
  64492. }
  64493. else {
  64494. notInDBCallback();
  64495. }
  64496. };
  64497. transaction.onabort = function (event) {
  64498. notInDBCallback();
  64499. };
  64500. var getRequest = transaction.objectStore(targetStore).get(url);
  64501. getRequest.onsuccess = function (event) {
  64502. file = (event.target).result;
  64503. };
  64504. getRequest.onerror = function (event) {
  64505. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  64506. notInDBCallback();
  64507. };
  64508. }
  64509. else {
  64510. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64511. callback();
  64512. }
  64513. };
  64514. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  64515. var _this = this;
  64516. if (this.isSupported) {
  64517. var targetStore;
  64518. if (url.indexOf(".babylon") !== -1) {
  64519. targetStore = "scenes";
  64520. }
  64521. else {
  64522. targetStore = "textures";
  64523. }
  64524. // Create XHR
  64525. var xhr = new XMLHttpRequest();
  64526. var fileData;
  64527. xhr.open("GET", url, true);
  64528. if (useArrayBuffer) {
  64529. xhr.responseType = "arraybuffer";
  64530. }
  64531. if (progressCallback) {
  64532. xhr.onprogress = progressCallback;
  64533. }
  64534. xhr.addEventListener("load", function () {
  64535. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  64536. // Blob as response (XHR2)
  64537. //fileData = xhr.responseText;
  64538. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  64539. if (!_this.hasReachedQuota && _this.db) {
  64540. // Open a transaction to the database
  64541. var transaction = _this.db.transaction([targetStore], "readwrite");
  64542. // the transaction could abort because of a QuotaExceededError error
  64543. transaction.onabort = function (event) {
  64544. try {
  64545. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  64546. var error = event.srcElement['error'];
  64547. if (error && error.name === "QuotaExceededError") {
  64548. _this.hasReachedQuota = true;
  64549. }
  64550. }
  64551. catch (ex) { }
  64552. callback(fileData);
  64553. };
  64554. transaction.oncomplete = function (event) {
  64555. callback(fileData);
  64556. };
  64557. var newFile;
  64558. if (targetStore === "scenes") {
  64559. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  64560. }
  64561. else {
  64562. newFile = { textureUrl: url, data: fileData };
  64563. }
  64564. try {
  64565. // Put the scene into the database
  64566. var addRequest = transaction.objectStore(targetStore).put(newFile);
  64567. addRequest.onsuccess = function (event) {
  64568. };
  64569. addRequest.onerror = function (event) {
  64570. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  64571. };
  64572. }
  64573. catch (ex) {
  64574. callback(fileData);
  64575. }
  64576. }
  64577. else {
  64578. callback(fileData);
  64579. }
  64580. }
  64581. else {
  64582. callback();
  64583. }
  64584. }, false);
  64585. xhr.addEventListener("error", function (event) {
  64586. BABYLON.Tools.Error("error on XHR request.");
  64587. callback();
  64588. }, false);
  64589. xhr.send();
  64590. }
  64591. else {
  64592. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  64593. callback();
  64594. }
  64595. };
  64596. Database.IsUASupportingBlobStorage = true;
  64597. Database.IDBStorageEnabled = true;
  64598. Database.parseURL = function (url) {
  64599. var a = document.createElement('a');
  64600. a.href = url;
  64601. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  64602. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  64603. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  64604. return absLocation;
  64605. };
  64606. Database.ReturnFullUrlLocation = function (url) {
  64607. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  64608. return (Database.parseURL(window.location.href) + url);
  64609. }
  64610. else {
  64611. return url;
  64612. }
  64613. };
  64614. return Database;
  64615. }());
  64616. BABYLON.Database = Database;
  64617. })(BABYLON || (BABYLON = {}));
  64618. //# sourceMappingURL=babylon.database.js.map
  64619. "use strict";
  64620. var BABYLON;
  64621. (function (BABYLON) {
  64622. var FresnelParameters = /** @class */ (function () {
  64623. function FresnelParameters() {
  64624. this._isEnabled = true;
  64625. this.leftColor = BABYLON.Color3.White();
  64626. this.rightColor = BABYLON.Color3.Black();
  64627. this.bias = 0;
  64628. this.power = 1;
  64629. }
  64630. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  64631. get: function () {
  64632. return this._isEnabled;
  64633. },
  64634. set: function (value) {
  64635. if (this._isEnabled === value) {
  64636. return;
  64637. }
  64638. this._isEnabled = value;
  64639. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  64640. },
  64641. enumerable: true,
  64642. configurable: true
  64643. });
  64644. FresnelParameters.prototype.clone = function () {
  64645. var newFresnelParameters = new FresnelParameters();
  64646. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  64647. return newFresnelParameters;
  64648. };
  64649. FresnelParameters.prototype.serialize = function () {
  64650. var serializationObject = {};
  64651. serializationObject.isEnabled = this.isEnabled;
  64652. serializationObject.leftColor = this.leftColor;
  64653. serializationObject.rightColor = this.rightColor;
  64654. serializationObject.bias = this.bias;
  64655. serializationObject.power = this.power;
  64656. return serializationObject;
  64657. };
  64658. FresnelParameters.Parse = function (parsedFresnelParameters) {
  64659. var fresnelParameters = new FresnelParameters();
  64660. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  64661. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  64662. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  64663. fresnelParameters.bias = parsedFresnelParameters.bias;
  64664. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  64665. return fresnelParameters;
  64666. };
  64667. return FresnelParameters;
  64668. }());
  64669. BABYLON.FresnelParameters = FresnelParameters;
  64670. })(BABYLON || (BABYLON = {}));
  64671. //# sourceMappingURL=babylon.fresnelParameters.js.map
  64672. "use strict";
  64673. var BABYLON;
  64674. (function (BABYLON) {
  64675. var MultiMaterial = /** @class */ (function (_super) {
  64676. __extends(MultiMaterial, _super);
  64677. function MultiMaterial(name, scene) {
  64678. var _this = _super.call(this, name, scene, true) || this;
  64679. scene.multiMaterials.push(_this);
  64680. _this.subMaterials = new Array();
  64681. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  64682. return _this;
  64683. }
  64684. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  64685. get: function () {
  64686. return this._subMaterials;
  64687. },
  64688. set: function (value) {
  64689. this._subMaterials = value;
  64690. this._hookArray(value);
  64691. },
  64692. enumerable: true,
  64693. configurable: true
  64694. });
  64695. MultiMaterial.prototype._hookArray = function (array) {
  64696. var _this = this;
  64697. var oldPush = array.push;
  64698. array.push = function () {
  64699. var items = [];
  64700. for (var _i = 0; _i < arguments.length; _i++) {
  64701. items[_i] = arguments[_i];
  64702. }
  64703. var result = oldPush.apply(array, items);
  64704. _this._markAllSubMeshesAsTexturesDirty();
  64705. return result;
  64706. };
  64707. var oldSplice = array.splice;
  64708. array.splice = function (index, deleteCount) {
  64709. var deleted = oldSplice.apply(array, [index, deleteCount]);
  64710. _this._markAllSubMeshesAsTexturesDirty();
  64711. return deleted;
  64712. };
  64713. };
  64714. // Properties
  64715. MultiMaterial.prototype.getSubMaterial = function (index) {
  64716. if (index < 0 || index >= this.subMaterials.length) {
  64717. return this.getScene().defaultMaterial;
  64718. }
  64719. return this.subMaterials[index];
  64720. };
  64721. MultiMaterial.prototype.getActiveTextures = function () {
  64722. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  64723. if (subMaterial) {
  64724. return subMaterial.getActiveTextures();
  64725. }
  64726. else {
  64727. return [];
  64728. }
  64729. }));
  64730. var _a;
  64731. };
  64732. // Methods
  64733. MultiMaterial.prototype.getClassName = function () {
  64734. return "MultiMaterial";
  64735. };
  64736. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  64737. for (var index = 0; index < this.subMaterials.length; index++) {
  64738. var subMaterial = this.subMaterials[index];
  64739. if (subMaterial) {
  64740. if (subMaterial.storeEffectOnSubMeshes) {
  64741. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  64742. return false;
  64743. }
  64744. continue;
  64745. }
  64746. if (!subMaterial.isReady(mesh)) {
  64747. return false;
  64748. }
  64749. }
  64750. }
  64751. return true;
  64752. };
  64753. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  64754. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  64755. for (var index = 0; index < this.subMaterials.length; index++) {
  64756. var subMaterial = null;
  64757. var current = this.subMaterials[index];
  64758. if (cloneChildren && current) {
  64759. subMaterial = current.clone(name + "-" + current.name);
  64760. }
  64761. else {
  64762. subMaterial = this.subMaterials[index];
  64763. }
  64764. newMultiMaterial.subMaterials.push(subMaterial);
  64765. }
  64766. return newMultiMaterial;
  64767. };
  64768. MultiMaterial.prototype.serialize = function () {
  64769. var serializationObject = {};
  64770. serializationObject.name = this.name;
  64771. serializationObject.id = this.id;
  64772. if (BABYLON.Tags) {
  64773. serializationObject.tags = BABYLON.Tags.GetTags(this);
  64774. }
  64775. serializationObject.materials = [];
  64776. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  64777. var subMat = this.subMaterials[matIndex];
  64778. if (subMat) {
  64779. serializationObject.materials.push(subMat.id);
  64780. }
  64781. else {
  64782. serializationObject.materials.push(null);
  64783. }
  64784. }
  64785. return serializationObject;
  64786. };
  64787. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  64788. var scene = this.getScene();
  64789. if (!scene) {
  64790. return;
  64791. }
  64792. var index = scene.multiMaterials.indexOf(this);
  64793. if (index >= 0) {
  64794. scene.multiMaterials.splice(index, 1);
  64795. }
  64796. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  64797. };
  64798. return MultiMaterial;
  64799. }(BABYLON.Material));
  64800. BABYLON.MultiMaterial = MultiMaterial;
  64801. })(BABYLON || (BABYLON = {}));
  64802. //# sourceMappingURL=babylon.multiMaterial.js.map
  64803. "use strict";
  64804. var BABYLON;
  64805. (function (BABYLON) {
  64806. var FreeCameraTouchInput = /** @class */ (function () {
  64807. function FreeCameraTouchInput() {
  64808. this._offsetX = null;
  64809. this._offsetY = null;
  64810. this._pointerPressed = new Array();
  64811. this.touchAngularSensibility = 200000.0;
  64812. this.touchMoveSensibility = 250.0;
  64813. }
  64814. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  64815. var _this = this;
  64816. var previousPosition = null;
  64817. if (this._pointerInput === undefined) {
  64818. this._onLostFocus = function (evt) {
  64819. _this._offsetX = null;
  64820. _this._offsetY = null;
  64821. };
  64822. this._pointerInput = function (p, s) {
  64823. var evt = p.event;
  64824. if (evt.pointerType === "mouse") {
  64825. return;
  64826. }
  64827. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  64828. if (!noPreventDefault) {
  64829. evt.preventDefault();
  64830. }
  64831. _this._pointerPressed.push(evt.pointerId);
  64832. if (_this._pointerPressed.length !== 1) {
  64833. return;
  64834. }
  64835. previousPosition = {
  64836. x: evt.clientX,
  64837. y: evt.clientY
  64838. };
  64839. }
  64840. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  64841. if (!noPreventDefault) {
  64842. evt.preventDefault();
  64843. }
  64844. var index = _this._pointerPressed.indexOf(evt.pointerId);
  64845. if (index === -1) {
  64846. return;
  64847. }
  64848. _this._pointerPressed.splice(index, 1);
  64849. if (index != 0) {
  64850. return;
  64851. }
  64852. previousPosition = null;
  64853. _this._offsetX = null;
  64854. _this._offsetY = null;
  64855. }
  64856. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  64857. if (!noPreventDefault) {
  64858. evt.preventDefault();
  64859. }
  64860. if (!previousPosition) {
  64861. return;
  64862. }
  64863. var index = _this._pointerPressed.indexOf(evt.pointerId);
  64864. if (index != 0) {
  64865. return;
  64866. }
  64867. _this._offsetX = evt.clientX - previousPosition.x;
  64868. _this._offsetY = -(evt.clientY - previousPosition.y);
  64869. }
  64870. };
  64871. }
  64872. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  64873. if (this._onLostFocus) {
  64874. element.addEventListener("blur", this._onLostFocus);
  64875. }
  64876. };
  64877. FreeCameraTouchInput.prototype.detachControl = function (element) {
  64878. if (this._pointerInput && element) {
  64879. if (this._observer) {
  64880. this.camera.getScene().onPointerObservable.remove(this._observer);
  64881. this._observer = null;
  64882. }
  64883. if (this._onLostFocus) {
  64884. element.removeEventListener("blur", this._onLostFocus);
  64885. this._onLostFocus = null;
  64886. }
  64887. this._pointerPressed = [];
  64888. this._offsetX = null;
  64889. this._offsetY = null;
  64890. }
  64891. };
  64892. FreeCameraTouchInput.prototype.checkInputs = function () {
  64893. if (this._offsetX && this._offsetY) {
  64894. var camera = this.camera;
  64895. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  64896. if (this._pointerPressed.length > 1) {
  64897. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  64898. }
  64899. else {
  64900. var speed = camera._computeLocalCameraSpeed();
  64901. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  64902. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  64903. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  64904. }
  64905. }
  64906. };
  64907. FreeCameraTouchInput.prototype.getClassName = function () {
  64908. return "FreeCameraTouchInput";
  64909. };
  64910. FreeCameraTouchInput.prototype.getSimpleName = function () {
  64911. return "touch";
  64912. };
  64913. __decorate([
  64914. BABYLON.serialize()
  64915. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  64916. __decorate([
  64917. BABYLON.serialize()
  64918. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  64919. return FreeCameraTouchInput;
  64920. }());
  64921. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  64922. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  64923. })(BABYLON || (BABYLON = {}));
  64924. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  64925. "use strict";
  64926. var BABYLON;
  64927. (function (BABYLON) {
  64928. // We're mainly based on the logic defined into the FreeCamera code
  64929. var TouchCamera = /** @class */ (function (_super) {
  64930. __extends(TouchCamera, _super);
  64931. //-- end properties for backward compatibility for inputs
  64932. function TouchCamera(name, position, scene) {
  64933. var _this = _super.call(this, name, position, scene) || this;
  64934. _this.inputs.addTouch();
  64935. _this._setupInputs();
  64936. return _this;
  64937. }
  64938. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  64939. //-- Begin properties for backward compatibility for inputs
  64940. get: function () {
  64941. var touch = this.inputs.attached["touch"];
  64942. if (touch)
  64943. return touch.touchAngularSensibility;
  64944. return 0;
  64945. },
  64946. set: function (value) {
  64947. var touch = this.inputs.attached["touch"];
  64948. if (touch)
  64949. touch.touchAngularSensibility = value;
  64950. },
  64951. enumerable: true,
  64952. configurable: true
  64953. });
  64954. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  64955. get: function () {
  64956. var touch = this.inputs.attached["touch"];
  64957. if (touch)
  64958. return touch.touchMoveSensibility;
  64959. return 0;
  64960. },
  64961. set: function (value) {
  64962. var touch = this.inputs.attached["touch"];
  64963. if (touch)
  64964. touch.touchMoveSensibility = value;
  64965. },
  64966. enumerable: true,
  64967. configurable: true
  64968. });
  64969. TouchCamera.prototype.getClassName = function () {
  64970. return "TouchCamera";
  64971. };
  64972. TouchCamera.prototype._setupInputs = function () {
  64973. var mouse = this.inputs.attached["mouse"];
  64974. if (mouse) {
  64975. mouse.touchEnabled = false;
  64976. }
  64977. };
  64978. return TouchCamera;
  64979. }(BABYLON.FreeCamera));
  64980. BABYLON.TouchCamera = TouchCamera;
  64981. })(BABYLON || (BABYLON = {}));
  64982. //# sourceMappingURL=babylon.touchCamera.js.map
  64983. "use strict";
  64984. var BABYLON;
  64985. (function (BABYLON) {
  64986. var ProceduralTexture = /** @class */ (function (_super) {
  64987. __extends(ProceduralTexture, _super);
  64988. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  64989. if (fallbackTexture === void 0) { fallbackTexture = null; }
  64990. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64991. if (isCube === void 0) { isCube = false; }
  64992. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  64993. _this.isCube = isCube;
  64994. _this.isEnabled = true;
  64995. _this._currentRefreshId = -1;
  64996. _this._refreshRate = 1;
  64997. _this._vertexBuffers = {};
  64998. _this._uniforms = new Array();
  64999. _this._samplers = new Array();
  65000. _this._textures = {};
  65001. _this._floats = {};
  65002. _this._floatsArrays = {};
  65003. _this._colors3 = {};
  65004. _this._colors4 = {};
  65005. _this._vectors2 = {};
  65006. _this._vectors3 = {};
  65007. _this._matrices = {};
  65008. _this._fallbackTextureUsed = false;
  65009. scene._proceduralTextures.push(_this);
  65010. _this._engine = scene.getEngine();
  65011. _this.name = name;
  65012. _this.isRenderTarget = true;
  65013. _this._size = size;
  65014. _this._generateMipMaps = generateMipMaps;
  65015. _this.setFragment(fragment);
  65016. _this._fallbackTexture = fallbackTexture;
  65017. if (isCube) {
  65018. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  65019. _this.setFloat("face", 0);
  65020. }
  65021. else {
  65022. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  65023. }
  65024. // VBO
  65025. var vertices = [];
  65026. vertices.push(1, 1);
  65027. vertices.push(-1, 1);
  65028. vertices.push(-1, -1);
  65029. vertices.push(1, -1);
  65030. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  65031. _this._createIndexBuffer();
  65032. return _this;
  65033. }
  65034. ProceduralTexture.prototype._createIndexBuffer = function () {
  65035. var engine = this._engine;
  65036. // Indices
  65037. var indices = [];
  65038. indices.push(0);
  65039. indices.push(1);
  65040. indices.push(2);
  65041. indices.push(0);
  65042. indices.push(2);
  65043. indices.push(3);
  65044. this._indexBuffer = engine.createIndexBuffer(indices);
  65045. };
  65046. ProceduralTexture.prototype._rebuild = function () {
  65047. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65048. if (vb) {
  65049. vb._rebuild();
  65050. }
  65051. this._createIndexBuffer();
  65052. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  65053. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  65054. }
  65055. };
  65056. ProceduralTexture.prototype.reset = function () {
  65057. if (this._effect === undefined) {
  65058. return;
  65059. }
  65060. var engine = this._engine;
  65061. engine._releaseEffect(this._effect);
  65062. };
  65063. ProceduralTexture.prototype.isReady = function () {
  65064. var _this = this;
  65065. var engine = this._engine;
  65066. var shaders;
  65067. if (!this._fragment) {
  65068. return false;
  65069. }
  65070. if (this._fallbackTextureUsed) {
  65071. return true;
  65072. }
  65073. if (this._fragment.fragmentElement !== undefined) {
  65074. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  65075. }
  65076. else {
  65077. shaders = { vertex: "procedural", fragment: this._fragment };
  65078. }
  65079. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  65080. _this.releaseInternalTexture();
  65081. if (_this._fallbackTexture) {
  65082. _this._texture = _this._fallbackTexture._texture;
  65083. if (_this._texture) {
  65084. _this._texture.incrementReferences();
  65085. }
  65086. }
  65087. _this._fallbackTextureUsed = true;
  65088. });
  65089. return this._effect.isReady();
  65090. };
  65091. ProceduralTexture.prototype.resetRefreshCounter = function () {
  65092. this._currentRefreshId = -1;
  65093. };
  65094. ProceduralTexture.prototype.setFragment = function (fragment) {
  65095. this._fragment = fragment;
  65096. };
  65097. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  65098. get: function () {
  65099. return this._refreshRate;
  65100. },
  65101. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  65102. set: function (value) {
  65103. this._refreshRate = value;
  65104. this.resetRefreshCounter();
  65105. },
  65106. enumerable: true,
  65107. configurable: true
  65108. });
  65109. ProceduralTexture.prototype._shouldRender = function () {
  65110. if (!this.isEnabled || !this.isReady() || !this._texture) {
  65111. return false;
  65112. }
  65113. if (this._fallbackTextureUsed) {
  65114. return false;
  65115. }
  65116. if (this._currentRefreshId === -1) {
  65117. this._currentRefreshId = 1;
  65118. return true;
  65119. }
  65120. if (this.refreshRate === this._currentRefreshId) {
  65121. this._currentRefreshId = 1;
  65122. return true;
  65123. }
  65124. this._currentRefreshId++;
  65125. return false;
  65126. };
  65127. ProceduralTexture.prototype.getRenderSize = function () {
  65128. return this._size;
  65129. };
  65130. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  65131. if (this._fallbackTextureUsed) {
  65132. return;
  65133. }
  65134. this.releaseInternalTexture();
  65135. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  65136. };
  65137. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  65138. if (this._uniforms.indexOf(uniformName) === -1) {
  65139. this._uniforms.push(uniformName);
  65140. }
  65141. };
  65142. ProceduralTexture.prototype.setTexture = function (name, texture) {
  65143. if (this._samplers.indexOf(name) === -1) {
  65144. this._samplers.push(name);
  65145. }
  65146. this._textures[name] = texture;
  65147. return this;
  65148. };
  65149. ProceduralTexture.prototype.setFloat = function (name, value) {
  65150. this._checkUniform(name);
  65151. this._floats[name] = value;
  65152. return this;
  65153. };
  65154. ProceduralTexture.prototype.setFloats = function (name, value) {
  65155. this._checkUniform(name);
  65156. this._floatsArrays[name] = value;
  65157. return this;
  65158. };
  65159. ProceduralTexture.prototype.setColor3 = function (name, value) {
  65160. this._checkUniform(name);
  65161. this._colors3[name] = value;
  65162. return this;
  65163. };
  65164. ProceduralTexture.prototype.setColor4 = function (name, value) {
  65165. this._checkUniform(name);
  65166. this._colors4[name] = value;
  65167. return this;
  65168. };
  65169. ProceduralTexture.prototype.setVector2 = function (name, value) {
  65170. this._checkUniform(name);
  65171. this._vectors2[name] = value;
  65172. return this;
  65173. };
  65174. ProceduralTexture.prototype.setVector3 = function (name, value) {
  65175. this._checkUniform(name);
  65176. this._vectors3[name] = value;
  65177. return this;
  65178. };
  65179. ProceduralTexture.prototype.setMatrix = function (name, value) {
  65180. this._checkUniform(name);
  65181. this._matrices[name] = value;
  65182. return this;
  65183. };
  65184. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  65185. var scene = this.getScene();
  65186. if (!scene) {
  65187. return;
  65188. }
  65189. var engine = this._engine;
  65190. // Render
  65191. engine.enableEffect(this._effect);
  65192. engine.setState(false);
  65193. // Texture
  65194. for (var name in this._textures) {
  65195. this._effect.setTexture(name, this._textures[name]);
  65196. }
  65197. // Float
  65198. for (name in this._floats) {
  65199. this._effect.setFloat(name, this._floats[name]);
  65200. }
  65201. // Floats
  65202. for (name in this._floatsArrays) {
  65203. this._effect.setArray(name, this._floatsArrays[name]);
  65204. }
  65205. // Color3
  65206. for (name in this._colors3) {
  65207. this._effect.setColor3(name, this._colors3[name]);
  65208. }
  65209. // Color4
  65210. for (name in this._colors4) {
  65211. var color = this._colors4[name];
  65212. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  65213. }
  65214. // Vector2
  65215. for (name in this._vectors2) {
  65216. this._effect.setVector2(name, this._vectors2[name]);
  65217. }
  65218. // Vector3
  65219. for (name in this._vectors3) {
  65220. this._effect.setVector3(name, this._vectors3[name]);
  65221. }
  65222. // Matrix
  65223. for (name in this._matrices) {
  65224. this._effect.setMatrix(name, this._matrices[name]);
  65225. }
  65226. if (!this._texture) {
  65227. return;
  65228. }
  65229. if (this.isCube) {
  65230. for (var face = 0; face < 6; face++) {
  65231. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  65232. // VBOs
  65233. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  65234. this._effect.setFloat("face", face);
  65235. // Clear
  65236. engine.clear(scene.clearColor, true, true, true);
  65237. // Draw order
  65238. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  65239. // Mipmaps
  65240. if (face === 5) {
  65241. engine.generateMipMapsForCubemap(this._texture);
  65242. }
  65243. }
  65244. }
  65245. else {
  65246. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  65247. // VBOs
  65248. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  65249. // Clear
  65250. engine.clear(scene.clearColor, true, true, true);
  65251. // Draw order
  65252. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  65253. }
  65254. // Unbind
  65255. engine.unBindFramebuffer(this._texture, this.isCube);
  65256. if (this.onGenerated) {
  65257. this.onGenerated();
  65258. }
  65259. };
  65260. ProceduralTexture.prototype.clone = function () {
  65261. var textureSize = this.getSize();
  65262. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  65263. // Base texture
  65264. newTexture.hasAlpha = this.hasAlpha;
  65265. newTexture.level = this.level;
  65266. // RenderTarget Texture
  65267. newTexture.coordinatesMode = this.coordinatesMode;
  65268. return newTexture;
  65269. };
  65270. ProceduralTexture.prototype.dispose = function () {
  65271. var scene = this.getScene();
  65272. if (!scene) {
  65273. return;
  65274. }
  65275. var index = scene._proceduralTextures.indexOf(this);
  65276. if (index >= 0) {
  65277. scene._proceduralTextures.splice(index, 1);
  65278. }
  65279. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65280. if (vertexBuffer) {
  65281. vertexBuffer.dispose();
  65282. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  65283. }
  65284. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  65285. this._indexBuffer = null;
  65286. }
  65287. _super.prototype.dispose.call(this);
  65288. };
  65289. return ProceduralTexture;
  65290. }(BABYLON.Texture));
  65291. BABYLON.ProceduralTexture = ProceduralTexture;
  65292. })(BABYLON || (BABYLON = {}));
  65293. //# sourceMappingURL=babylon.proceduralTexture.js.map
  65294. "use strict";
  65295. var BABYLON;
  65296. (function (BABYLON) {
  65297. var CustomProceduralTexture = /** @class */ (function (_super) {
  65298. __extends(CustomProceduralTexture, _super);
  65299. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  65300. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  65301. _this._animate = true;
  65302. _this._time = 0;
  65303. _this._texturePath = texturePath;
  65304. //Try to load json
  65305. _this.loadJson(texturePath);
  65306. _this.refreshRate = 1;
  65307. return _this;
  65308. }
  65309. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  65310. var _this = this;
  65311. var noConfigFile = function () {
  65312. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  65313. try {
  65314. _this.setFragment(_this._texturePath);
  65315. }
  65316. catch (ex) {
  65317. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  65318. }
  65319. };
  65320. var configFileUrl = jsonUrl + "/config.json";
  65321. var xhr = new XMLHttpRequest();
  65322. xhr.open("GET", configFileUrl, true);
  65323. xhr.addEventListener("load", function () {
  65324. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  65325. try {
  65326. _this._config = JSON.parse(xhr.response);
  65327. _this.updateShaderUniforms();
  65328. _this.updateTextures();
  65329. _this.setFragment(_this._texturePath + "/custom");
  65330. _this._animate = _this._config.animate;
  65331. _this.refreshRate = _this._config.refreshrate;
  65332. }
  65333. catch (ex) {
  65334. noConfigFile();
  65335. }
  65336. }
  65337. else {
  65338. noConfigFile();
  65339. }
  65340. }, false);
  65341. xhr.addEventListener("error", function () {
  65342. noConfigFile();
  65343. }, false);
  65344. try {
  65345. xhr.send();
  65346. }
  65347. catch (ex) {
  65348. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  65349. }
  65350. };
  65351. CustomProceduralTexture.prototype.isReady = function () {
  65352. if (!_super.prototype.isReady.call(this)) {
  65353. return false;
  65354. }
  65355. for (var name in this._textures) {
  65356. var texture = this._textures[name];
  65357. if (!texture.isReady()) {
  65358. return false;
  65359. }
  65360. }
  65361. return true;
  65362. };
  65363. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  65364. var scene = this.getScene();
  65365. if (this._animate && scene) {
  65366. this._time += scene.getAnimationRatio() * 0.03;
  65367. this.updateShaderUniforms();
  65368. }
  65369. _super.prototype.render.call(this, useCameraPostProcess);
  65370. };
  65371. CustomProceduralTexture.prototype.updateTextures = function () {
  65372. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  65373. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  65374. }
  65375. };
  65376. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  65377. if (this._config) {
  65378. for (var j = 0; j < this._config.uniforms.length; j++) {
  65379. var uniform = this._config.uniforms[j];
  65380. switch (uniform.type) {
  65381. case "float":
  65382. this.setFloat(uniform.name, uniform.value);
  65383. break;
  65384. case "color3":
  65385. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  65386. break;
  65387. case "color4":
  65388. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  65389. break;
  65390. case "vector2":
  65391. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  65392. break;
  65393. case "vector3":
  65394. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  65395. break;
  65396. }
  65397. }
  65398. }
  65399. this.setFloat("time", this._time);
  65400. };
  65401. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  65402. get: function () {
  65403. return this._animate;
  65404. },
  65405. set: function (value) {
  65406. this._animate = value;
  65407. },
  65408. enumerable: true,
  65409. configurable: true
  65410. });
  65411. return CustomProceduralTexture;
  65412. }(BABYLON.ProceduralTexture));
  65413. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  65414. })(BABYLON || (BABYLON = {}));
  65415. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  65416. "use strict";
  65417. var BABYLON;
  65418. (function (BABYLON) {
  65419. var FreeCameraGamepadInput = /** @class */ (function () {
  65420. function FreeCameraGamepadInput() {
  65421. this.gamepadAngularSensibility = 200;
  65422. this.gamepadMoveSensibility = 40;
  65423. // private members
  65424. this._cameraTransform = BABYLON.Matrix.Identity();
  65425. this._deltaTransform = BABYLON.Vector3.Zero();
  65426. this._vector3 = BABYLON.Vector3.Zero();
  65427. this._vector2 = BABYLON.Vector2.Zero();
  65428. }
  65429. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  65430. var _this = this;
  65431. var manager = this.camera.getScene().gamepadManager;
  65432. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  65433. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  65434. // prioritize XBOX gamepads.
  65435. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  65436. _this.gamepad = gamepad;
  65437. }
  65438. }
  65439. });
  65440. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  65441. if (_this.gamepad === gamepad) {
  65442. _this.gamepad = null;
  65443. }
  65444. });
  65445. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  65446. };
  65447. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  65448. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  65449. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  65450. this.gamepad = null;
  65451. };
  65452. FreeCameraGamepadInput.prototype.checkInputs = function () {
  65453. if (this.gamepad && this.gamepad.leftStick) {
  65454. var camera = this.camera;
  65455. var LSValues = this.gamepad.leftStick;
  65456. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  65457. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  65458. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  65459. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  65460. var RSValues = this.gamepad.rightStick;
  65461. if (RSValues) {
  65462. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  65463. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  65464. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  65465. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  65466. }
  65467. else {
  65468. RSValues = { x: 0, y: 0 };
  65469. }
  65470. if (!camera.rotationQuaternion) {
  65471. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  65472. }
  65473. else {
  65474. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  65475. }
  65476. var speed = camera._computeLocalCameraSpeed() * 50.0;
  65477. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  65478. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  65479. camera.cameraDirection.addInPlace(this._deltaTransform);
  65480. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  65481. camera.cameraRotation.addInPlace(this._vector2);
  65482. }
  65483. };
  65484. FreeCameraGamepadInput.prototype.getClassName = function () {
  65485. return "FreeCameraGamepadInput";
  65486. };
  65487. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  65488. return "gamepad";
  65489. };
  65490. __decorate([
  65491. BABYLON.serialize()
  65492. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  65493. __decorate([
  65494. BABYLON.serialize()
  65495. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  65496. return FreeCameraGamepadInput;
  65497. }());
  65498. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  65499. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  65500. })(BABYLON || (BABYLON = {}));
  65501. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  65502. "use strict";
  65503. var BABYLON;
  65504. (function (BABYLON) {
  65505. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  65506. function ArcRotateCameraGamepadInput() {
  65507. this.gamepadRotationSensibility = 80;
  65508. this.gamepadMoveSensibility = 40;
  65509. }
  65510. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  65511. var _this = this;
  65512. var manager = this.camera.getScene().gamepadManager;
  65513. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  65514. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  65515. // prioritize XBOX gamepads.
  65516. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  65517. _this.gamepad = gamepad;
  65518. }
  65519. }
  65520. });
  65521. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  65522. if (_this.gamepad === gamepad) {
  65523. _this.gamepad = null;
  65524. }
  65525. });
  65526. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  65527. };
  65528. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  65529. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  65530. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  65531. this.gamepad = null;
  65532. };
  65533. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  65534. if (this.gamepad) {
  65535. var camera = this.camera;
  65536. var RSValues = this.gamepad.rightStick;
  65537. if (RSValues) {
  65538. if (RSValues.x != 0) {
  65539. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  65540. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  65541. camera.inertialAlphaOffset += normalizedRX;
  65542. }
  65543. }
  65544. if (RSValues.y != 0) {
  65545. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  65546. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  65547. camera.inertialBetaOffset += normalizedRY;
  65548. }
  65549. }
  65550. }
  65551. var LSValues = this.gamepad.leftStick;
  65552. if (LSValues && LSValues.y != 0) {
  65553. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  65554. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  65555. this.camera.inertialRadiusOffset -= normalizedLY;
  65556. }
  65557. }
  65558. }
  65559. };
  65560. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  65561. return "ArcRotateCameraGamepadInput";
  65562. };
  65563. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  65564. return "gamepad";
  65565. };
  65566. __decorate([
  65567. BABYLON.serialize()
  65568. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  65569. __decorate([
  65570. BABYLON.serialize()
  65571. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  65572. return ArcRotateCameraGamepadInput;
  65573. }());
  65574. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  65575. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  65576. })(BABYLON || (BABYLON = {}));
  65577. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  65578. "use strict";
  65579. var BABYLON;
  65580. (function (BABYLON) {
  65581. var GamepadManager = /** @class */ (function () {
  65582. function GamepadManager(_scene) {
  65583. var _this = this;
  65584. this._scene = _scene;
  65585. this._babylonGamepads = [];
  65586. this._oneGamepadConnected = false;
  65587. this._isMonitoring = false;
  65588. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  65589. if (!BABYLON.Tools.IsWindowObjectExist()) {
  65590. this._gamepadEventSupported = false;
  65591. }
  65592. else {
  65593. this._gamepadEventSupported = 'GamepadEvent' in window;
  65594. this._gamepadSupport = (navigator.getGamepads ||
  65595. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  65596. }
  65597. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  65598. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  65599. for (var i in _this._babylonGamepads) {
  65600. var gamepad = _this._babylonGamepads[i];
  65601. if (gamepad && gamepad._isConnected) {
  65602. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  65603. }
  65604. }
  65605. });
  65606. this._onGamepadConnectedEvent = function (evt) {
  65607. var gamepad = evt.gamepad;
  65608. if (gamepad.index in _this._babylonGamepads) {
  65609. if (_this._babylonGamepads[gamepad.index].isConnected) {
  65610. return;
  65611. }
  65612. }
  65613. var newGamepad;
  65614. if (_this._babylonGamepads[gamepad.index]) {
  65615. newGamepad = _this._babylonGamepads[gamepad.index];
  65616. newGamepad.browserGamepad = gamepad;
  65617. newGamepad._isConnected = true;
  65618. }
  65619. else {
  65620. newGamepad = _this._addNewGamepad(gamepad);
  65621. }
  65622. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  65623. _this._startMonitoringGamepads();
  65624. };
  65625. this._onGamepadDisconnectedEvent = function (evt) {
  65626. var gamepad = evt.gamepad;
  65627. // Remove the gamepad from the list of gamepads to monitor.
  65628. for (var i in _this._babylonGamepads) {
  65629. if (_this._babylonGamepads[i].index === gamepad.index) {
  65630. var disconnectedGamepad = _this._babylonGamepads[i];
  65631. disconnectedGamepad._isConnected = false;
  65632. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  65633. break;
  65634. }
  65635. }
  65636. };
  65637. if (this._gamepadSupport) {
  65638. //first add already-connected gamepads
  65639. this._updateGamepadObjects();
  65640. if (this._babylonGamepads.length) {
  65641. this._startMonitoringGamepads();
  65642. }
  65643. // Checking if the gamepad connected event is supported (like in Firefox)
  65644. if (this._gamepadEventSupported) {
  65645. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  65646. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  65647. }
  65648. else {
  65649. this._startMonitoringGamepads();
  65650. }
  65651. }
  65652. }
  65653. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  65654. get: function () {
  65655. return this._babylonGamepads;
  65656. },
  65657. enumerable: true,
  65658. configurable: true
  65659. });
  65660. GamepadManager.prototype.getGamepadByType = function (type) {
  65661. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  65662. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  65663. var gamepad = _a[_i];
  65664. if (gamepad && gamepad.type === type) {
  65665. return gamepad;
  65666. }
  65667. }
  65668. return null;
  65669. };
  65670. GamepadManager.prototype.dispose = function () {
  65671. if (this._gamepadEventSupported) {
  65672. if (this._onGamepadConnectedEvent) {
  65673. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  65674. }
  65675. if (this._onGamepadDisconnectedEvent) {
  65676. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  65677. }
  65678. this._onGamepadConnectedEvent = null;
  65679. this._onGamepadDisconnectedEvent = null;
  65680. }
  65681. this._babylonGamepads.forEach(function (gamepad) {
  65682. gamepad.dispose();
  65683. });
  65684. this.onGamepadConnectedObservable.clear();
  65685. this.onGamepadDisconnectedObservable.clear();
  65686. this._oneGamepadConnected = false;
  65687. this._stopMonitoringGamepads();
  65688. this._babylonGamepads = [];
  65689. };
  65690. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  65691. if (!this._oneGamepadConnected) {
  65692. this._oneGamepadConnected = true;
  65693. }
  65694. var newGamepad;
  65695. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  65696. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  65697. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  65698. }
  65699. else if (gamepad.pose) {
  65700. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  65701. }
  65702. else {
  65703. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  65704. }
  65705. this._babylonGamepads[newGamepad.index] = newGamepad;
  65706. return newGamepad;
  65707. };
  65708. GamepadManager.prototype._startMonitoringGamepads = function () {
  65709. if (!this._isMonitoring) {
  65710. this._isMonitoring = true;
  65711. //back-comp
  65712. if (!this._scene) {
  65713. this._checkGamepadsStatus();
  65714. }
  65715. }
  65716. };
  65717. GamepadManager.prototype._stopMonitoringGamepads = function () {
  65718. this._isMonitoring = false;
  65719. };
  65720. GamepadManager.prototype._checkGamepadsStatus = function () {
  65721. var _this = this;
  65722. // Hack to be compatible Chrome
  65723. this._updateGamepadObjects();
  65724. for (var i in this._babylonGamepads) {
  65725. var gamepad = this._babylonGamepads[i];
  65726. if (!gamepad || !gamepad.isConnected) {
  65727. continue;
  65728. }
  65729. gamepad.update();
  65730. }
  65731. if (this._isMonitoring && !this._scene) {
  65732. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  65733. }
  65734. };
  65735. // This function is called only on Chrome, which does not properly support
  65736. // connection/disconnection events and forces you to recopy again the gamepad object
  65737. GamepadManager.prototype._updateGamepadObjects = function () {
  65738. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  65739. for (var i = 0; i < gamepads.length; i++) {
  65740. if (gamepads[i]) {
  65741. if (!this._babylonGamepads[gamepads[i].index]) {
  65742. var newGamepad = this._addNewGamepad(gamepads[i]);
  65743. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  65744. }
  65745. else {
  65746. // Forced to copy again this object for Chrome for unknown reason
  65747. this._babylonGamepads[i].browserGamepad = gamepads[i];
  65748. if (!this._babylonGamepads[i].isConnected) {
  65749. this._babylonGamepads[i]._isConnected = true;
  65750. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  65751. }
  65752. }
  65753. }
  65754. }
  65755. };
  65756. return GamepadManager;
  65757. }());
  65758. BABYLON.GamepadManager = GamepadManager;
  65759. })(BABYLON || (BABYLON = {}));
  65760. //# sourceMappingURL=babylon.gamepadManager.js.map
  65761. "use strict";
  65762. var BABYLON;
  65763. (function (BABYLON) {
  65764. var StickValues = /** @class */ (function () {
  65765. function StickValues(x, y) {
  65766. this.x = x;
  65767. this.y = y;
  65768. }
  65769. return StickValues;
  65770. }());
  65771. BABYLON.StickValues = StickValues;
  65772. var Gamepad = /** @class */ (function () {
  65773. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  65774. if (leftStickX === void 0) { leftStickX = 0; }
  65775. if (leftStickY === void 0) { leftStickY = 1; }
  65776. if (rightStickX === void 0) { rightStickX = 2; }
  65777. if (rightStickY === void 0) { rightStickY = 3; }
  65778. this.id = id;
  65779. this.index = index;
  65780. this.browserGamepad = browserGamepad;
  65781. this._isConnected = true;
  65782. this._invertLeftStickY = false;
  65783. this.type = Gamepad.GAMEPAD;
  65784. this._leftStickAxisX = leftStickX;
  65785. this._leftStickAxisY = leftStickY;
  65786. this._rightStickAxisX = rightStickX;
  65787. this._rightStickAxisY = rightStickY;
  65788. if (this.browserGamepad.axes.length >= 2) {
  65789. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  65790. }
  65791. if (this.browserGamepad.axes.length >= 4) {
  65792. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  65793. }
  65794. }
  65795. Object.defineProperty(Gamepad.prototype, "isConnected", {
  65796. get: function () {
  65797. return this._isConnected;
  65798. },
  65799. enumerable: true,
  65800. configurable: true
  65801. });
  65802. Gamepad.prototype.onleftstickchanged = function (callback) {
  65803. this._onleftstickchanged = callback;
  65804. };
  65805. Gamepad.prototype.onrightstickchanged = function (callback) {
  65806. this._onrightstickchanged = callback;
  65807. };
  65808. Object.defineProperty(Gamepad.prototype, "leftStick", {
  65809. get: function () {
  65810. return this._leftStick;
  65811. },
  65812. set: function (newValues) {
  65813. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  65814. this._onleftstickchanged(newValues);
  65815. }
  65816. this._leftStick = newValues;
  65817. },
  65818. enumerable: true,
  65819. configurable: true
  65820. });
  65821. Object.defineProperty(Gamepad.prototype, "rightStick", {
  65822. get: function () {
  65823. return this._rightStick;
  65824. },
  65825. set: function (newValues) {
  65826. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  65827. this._onrightstickchanged(newValues);
  65828. }
  65829. this._rightStick = newValues;
  65830. },
  65831. enumerable: true,
  65832. configurable: true
  65833. });
  65834. Gamepad.prototype.update = function () {
  65835. if (this._leftStick) {
  65836. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  65837. if (this._invertLeftStickY) {
  65838. this.leftStick.y *= -1;
  65839. }
  65840. }
  65841. if (this._rightStick) {
  65842. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  65843. }
  65844. };
  65845. Gamepad.prototype.dispose = function () {
  65846. };
  65847. Gamepad.GAMEPAD = 0;
  65848. Gamepad.GENERIC = 1;
  65849. Gamepad.XBOX = 2;
  65850. Gamepad.POSE_ENABLED = 3;
  65851. return Gamepad;
  65852. }());
  65853. BABYLON.Gamepad = Gamepad;
  65854. var GenericPad = /** @class */ (function (_super) {
  65855. __extends(GenericPad, _super);
  65856. function GenericPad(id, index, browserGamepad) {
  65857. var _this = _super.call(this, id, index, browserGamepad) || this;
  65858. _this.onButtonDownObservable = new BABYLON.Observable();
  65859. _this.onButtonUpObservable = new BABYLON.Observable();
  65860. _this.type = Gamepad.GENERIC;
  65861. _this._buttons = new Array(browserGamepad.buttons.length);
  65862. return _this;
  65863. }
  65864. GenericPad.prototype.onbuttondown = function (callback) {
  65865. this._onbuttondown = callback;
  65866. };
  65867. GenericPad.prototype.onbuttonup = function (callback) {
  65868. this._onbuttonup = callback;
  65869. };
  65870. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  65871. if (newValue !== currentValue) {
  65872. if (newValue === 1) {
  65873. if (this._onbuttondown) {
  65874. this._onbuttondown(buttonIndex);
  65875. }
  65876. this.onButtonDownObservable.notifyObservers(buttonIndex);
  65877. }
  65878. if (newValue === 0) {
  65879. if (this._onbuttonup) {
  65880. this._onbuttonup(buttonIndex);
  65881. }
  65882. this.onButtonUpObservable.notifyObservers(buttonIndex);
  65883. }
  65884. }
  65885. return newValue;
  65886. };
  65887. GenericPad.prototype.update = function () {
  65888. _super.prototype.update.call(this);
  65889. for (var index = 0; index < this._buttons.length; index++) {
  65890. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  65891. }
  65892. };
  65893. GenericPad.prototype.dispose = function () {
  65894. _super.prototype.dispose.call(this);
  65895. this.onButtonDownObservable.clear();
  65896. this.onButtonUpObservable.clear();
  65897. };
  65898. return GenericPad;
  65899. }(Gamepad));
  65900. BABYLON.GenericPad = GenericPad;
  65901. })(BABYLON || (BABYLON = {}));
  65902. //# sourceMappingURL=babylon.gamepad.js.map
  65903. "use strict";
  65904. var BABYLON;
  65905. (function (BABYLON) {
  65906. var Xbox360Button;
  65907. (function (Xbox360Button) {
  65908. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  65909. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  65910. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  65911. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  65912. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  65913. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  65914. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  65915. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  65916. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  65917. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  65918. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  65919. var Xbox360Dpad;
  65920. (function (Xbox360Dpad) {
  65921. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  65922. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  65923. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  65924. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  65925. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  65926. var Xbox360Pad = /** @class */ (function (_super) {
  65927. __extends(Xbox360Pad, _super);
  65928. function Xbox360Pad(id, index, gamepad, xboxOne) {
  65929. if (xboxOne === void 0) { xboxOne = false; }
  65930. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  65931. _this._leftTrigger = 0;
  65932. _this._rightTrigger = 0;
  65933. _this.onButtonDownObservable = new BABYLON.Observable();
  65934. _this.onButtonUpObservable = new BABYLON.Observable();
  65935. _this.onPadDownObservable = new BABYLON.Observable();
  65936. _this.onPadUpObservable = new BABYLON.Observable();
  65937. _this._buttonA = 0;
  65938. _this._buttonB = 0;
  65939. _this._buttonX = 0;
  65940. _this._buttonY = 0;
  65941. _this._buttonBack = 0;
  65942. _this._buttonStart = 0;
  65943. _this._buttonLB = 0;
  65944. _this._buttonRB = 0;
  65945. _this._buttonLeftStick = 0;
  65946. _this._buttonRightStick = 0;
  65947. _this._dPadUp = 0;
  65948. _this._dPadDown = 0;
  65949. _this._dPadLeft = 0;
  65950. _this._dPadRight = 0;
  65951. _this._isXboxOnePad = false;
  65952. _this.type = BABYLON.Gamepad.XBOX;
  65953. _this._isXboxOnePad = xboxOne;
  65954. return _this;
  65955. }
  65956. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  65957. this._onlefttriggerchanged = callback;
  65958. };
  65959. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  65960. this._onrighttriggerchanged = callback;
  65961. };
  65962. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  65963. get: function () {
  65964. return this._leftTrigger;
  65965. },
  65966. set: function (newValue) {
  65967. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  65968. this._onlefttriggerchanged(newValue);
  65969. }
  65970. this._leftTrigger = newValue;
  65971. },
  65972. enumerable: true,
  65973. configurable: true
  65974. });
  65975. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  65976. get: function () {
  65977. return this._rightTrigger;
  65978. },
  65979. set: function (newValue) {
  65980. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  65981. this._onrighttriggerchanged(newValue);
  65982. }
  65983. this._rightTrigger = newValue;
  65984. },
  65985. enumerable: true,
  65986. configurable: true
  65987. });
  65988. Xbox360Pad.prototype.onbuttondown = function (callback) {
  65989. this._onbuttondown = callback;
  65990. };
  65991. Xbox360Pad.prototype.onbuttonup = function (callback) {
  65992. this._onbuttonup = callback;
  65993. };
  65994. Xbox360Pad.prototype.ondpaddown = function (callback) {
  65995. this._ondpaddown = callback;
  65996. };
  65997. Xbox360Pad.prototype.ondpadup = function (callback) {
  65998. this._ondpadup = callback;
  65999. };
  66000. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  66001. if (newValue !== currentValue) {
  66002. if (newValue === 1) {
  66003. if (this._onbuttondown) {
  66004. this._onbuttondown(buttonType);
  66005. }
  66006. this.onButtonDownObservable.notifyObservers(buttonType);
  66007. }
  66008. if (newValue === 0) {
  66009. if (this._onbuttonup) {
  66010. this._onbuttonup(buttonType);
  66011. }
  66012. this.onButtonUpObservable.notifyObservers(buttonType);
  66013. }
  66014. }
  66015. return newValue;
  66016. };
  66017. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  66018. if (newValue !== currentValue) {
  66019. if (newValue === 1) {
  66020. if (this._ondpaddown) {
  66021. this._ondpaddown(buttonType);
  66022. }
  66023. this.onPadDownObservable.notifyObservers(buttonType);
  66024. }
  66025. if (newValue === 0) {
  66026. if (this._ondpadup) {
  66027. this._ondpadup(buttonType);
  66028. }
  66029. this.onPadUpObservable.notifyObservers(buttonType);
  66030. }
  66031. }
  66032. return newValue;
  66033. };
  66034. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  66035. get: function () {
  66036. return this._buttonA;
  66037. },
  66038. set: function (value) {
  66039. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  66040. },
  66041. enumerable: true,
  66042. configurable: true
  66043. });
  66044. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  66045. get: function () {
  66046. return this._buttonB;
  66047. },
  66048. set: function (value) {
  66049. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  66050. },
  66051. enumerable: true,
  66052. configurable: true
  66053. });
  66054. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  66055. get: function () {
  66056. return this._buttonX;
  66057. },
  66058. set: function (value) {
  66059. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  66060. },
  66061. enumerable: true,
  66062. configurable: true
  66063. });
  66064. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  66065. get: function () {
  66066. return this._buttonY;
  66067. },
  66068. set: function (value) {
  66069. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  66070. },
  66071. enumerable: true,
  66072. configurable: true
  66073. });
  66074. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  66075. get: function () {
  66076. return this._buttonStart;
  66077. },
  66078. set: function (value) {
  66079. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  66080. },
  66081. enumerable: true,
  66082. configurable: true
  66083. });
  66084. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  66085. get: function () {
  66086. return this._buttonBack;
  66087. },
  66088. set: function (value) {
  66089. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  66090. },
  66091. enumerable: true,
  66092. configurable: true
  66093. });
  66094. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  66095. get: function () {
  66096. return this._buttonLB;
  66097. },
  66098. set: function (value) {
  66099. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  66100. },
  66101. enumerable: true,
  66102. configurable: true
  66103. });
  66104. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  66105. get: function () {
  66106. return this._buttonRB;
  66107. },
  66108. set: function (value) {
  66109. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  66110. },
  66111. enumerable: true,
  66112. configurable: true
  66113. });
  66114. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  66115. get: function () {
  66116. return this._buttonLeftStick;
  66117. },
  66118. set: function (value) {
  66119. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  66120. },
  66121. enumerable: true,
  66122. configurable: true
  66123. });
  66124. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  66125. get: function () {
  66126. return this._buttonRightStick;
  66127. },
  66128. set: function (value) {
  66129. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  66130. },
  66131. enumerable: true,
  66132. configurable: true
  66133. });
  66134. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  66135. get: function () {
  66136. return this._dPadUp;
  66137. },
  66138. set: function (value) {
  66139. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  66140. },
  66141. enumerable: true,
  66142. configurable: true
  66143. });
  66144. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  66145. get: function () {
  66146. return this._dPadDown;
  66147. },
  66148. set: function (value) {
  66149. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  66150. },
  66151. enumerable: true,
  66152. configurable: true
  66153. });
  66154. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  66155. get: function () {
  66156. return this._dPadLeft;
  66157. },
  66158. set: function (value) {
  66159. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  66160. },
  66161. enumerable: true,
  66162. configurable: true
  66163. });
  66164. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  66165. get: function () {
  66166. return this._dPadRight;
  66167. },
  66168. set: function (value) {
  66169. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  66170. },
  66171. enumerable: true,
  66172. configurable: true
  66173. });
  66174. Xbox360Pad.prototype.update = function () {
  66175. _super.prototype.update.call(this);
  66176. if (this._isXboxOnePad) {
  66177. this.buttonA = this.browserGamepad.buttons[0].value;
  66178. this.buttonB = this.browserGamepad.buttons[1].value;
  66179. this.buttonX = this.browserGamepad.buttons[2].value;
  66180. this.buttonY = this.browserGamepad.buttons[3].value;
  66181. this.buttonLB = this.browserGamepad.buttons[4].value;
  66182. this.buttonRB = this.browserGamepad.buttons[5].value;
  66183. this.leftTrigger = this.browserGamepad.axes[2];
  66184. this.rightTrigger = this.browserGamepad.axes[5];
  66185. this.buttonBack = this.browserGamepad.buttons[9].value;
  66186. this.buttonStart = this.browserGamepad.buttons[8].value;
  66187. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  66188. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  66189. this.dPadUp = this.browserGamepad.buttons[11].value;
  66190. this.dPadDown = this.browserGamepad.buttons[12].value;
  66191. this.dPadLeft = this.browserGamepad.buttons[13].value;
  66192. this.dPadRight = this.browserGamepad.buttons[14].value;
  66193. }
  66194. else {
  66195. this.buttonA = this.browserGamepad.buttons[0].value;
  66196. this.buttonB = this.browserGamepad.buttons[1].value;
  66197. this.buttonX = this.browserGamepad.buttons[2].value;
  66198. this.buttonY = this.browserGamepad.buttons[3].value;
  66199. this.buttonLB = this.browserGamepad.buttons[4].value;
  66200. this.buttonRB = this.browserGamepad.buttons[5].value;
  66201. this.leftTrigger = this.browserGamepad.buttons[6].value;
  66202. this.rightTrigger = this.browserGamepad.buttons[7].value;
  66203. this.buttonBack = this.browserGamepad.buttons[8].value;
  66204. this.buttonStart = this.browserGamepad.buttons[9].value;
  66205. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  66206. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  66207. this.dPadUp = this.browserGamepad.buttons[12].value;
  66208. this.dPadDown = this.browserGamepad.buttons[13].value;
  66209. this.dPadLeft = this.browserGamepad.buttons[14].value;
  66210. this.dPadRight = this.browserGamepad.buttons[15].value;
  66211. }
  66212. };
  66213. Xbox360Pad.prototype.dispose = function () {
  66214. _super.prototype.dispose.call(this);
  66215. this.onButtonDownObservable.clear();
  66216. this.onButtonUpObservable.clear();
  66217. this.onPadDownObservable.clear();
  66218. this.onPadUpObservable.clear();
  66219. };
  66220. return Xbox360Pad;
  66221. }(BABYLON.Gamepad));
  66222. BABYLON.Xbox360Pad = Xbox360Pad;
  66223. })(BABYLON || (BABYLON = {}));
  66224. //# sourceMappingURL=babylon.xboxGamepad.js.map
  66225. "use strict";
  66226. var BABYLON;
  66227. (function (BABYLON) {
  66228. var PoseEnabledControllerType;
  66229. (function (PoseEnabledControllerType) {
  66230. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  66231. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  66232. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  66233. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  66234. /**
  66235. * Google Daydream
  66236. */
  66237. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  66238. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  66239. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  66240. var PoseEnabledControllerHelper = /** @class */ (function () {
  66241. function PoseEnabledControllerHelper() {
  66242. }
  66243. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  66244. // Oculus Touch
  66245. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  66246. return new BABYLON.OculusTouchController(vrGamepad);
  66247. }
  66248. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  66249. return new BABYLON.WindowsMotionController(vrGamepad);
  66250. }
  66251. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  66252. return new BABYLON.ViveController(vrGamepad);
  66253. }
  66254. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  66255. return new BABYLON.GearVRController(vrGamepad);
  66256. }
  66257. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  66258. return new BABYLON.DaydreamController(vrGamepad);
  66259. }
  66260. else {
  66261. return new BABYLON.GenericController(vrGamepad);
  66262. }
  66263. };
  66264. return PoseEnabledControllerHelper;
  66265. }());
  66266. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  66267. var PoseEnabledController = /** @class */ (function (_super) {
  66268. __extends(PoseEnabledController, _super);
  66269. function PoseEnabledController(browserGamepad) {
  66270. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  66271. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  66272. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  66273. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  66274. // Represents device position and rotation in babylon space
  66275. _this.devicePosition = BABYLON.Vector3.Zero();
  66276. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  66277. _this.deviceScaleFactor = 1;
  66278. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  66279. _this._deviceToWorld = BABYLON.Matrix.Identity();
  66280. /**
  66281. * Node to be used when casting a ray from the controller
  66282. */
  66283. _this._pointingPoseNode = null;
  66284. _this._workingMatrix = BABYLON.Matrix.Identity();
  66285. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  66286. _this.controllerType = PoseEnabledControllerType.GENERIC;
  66287. _this.position = BABYLON.Vector3.Zero();
  66288. _this.rotationQuaternion = new BABYLON.Quaternion();
  66289. _this._calculatedPosition = BABYLON.Vector3.Zero();
  66290. _this._calculatedRotation = new BABYLON.Quaternion();
  66291. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  66292. return _this;
  66293. }
  66294. PoseEnabledController.prototype.update = function () {
  66295. _super.prototype.update.call(this);
  66296. var pose = this.browserGamepad.pose;
  66297. this.updateFromDevice(pose);
  66298. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  66299. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  66300. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  66301. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  66302. if (this._mesh) {
  66303. this._mesh.position.copyFrom(this.devicePosition);
  66304. if (this._mesh.rotationQuaternion) {
  66305. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  66306. }
  66307. }
  66308. };
  66309. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  66310. if (poseData) {
  66311. this.rawPose = poseData;
  66312. if (poseData.position) {
  66313. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  66314. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  66315. this._deviceRoomPosition.z *= -1;
  66316. }
  66317. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  66318. this._calculatedPosition.addInPlace(this.position);
  66319. }
  66320. var pose = this.rawPose;
  66321. if (poseData.orientation && pose.orientation) {
  66322. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  66323. if (this._mesh) {
  66324. if (this._mesh.getScene().useRightHandedSystem) {
  66325. this._deviceRoomRotationQuaternion.z *= -1;
  66326. this._deviceRoomRotationQuaternion.w *= -1;
  66327. }
  66328. else {
  66329. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  66330. }
  66331. }
  66332. // if the camera is set, rotate to the camera's rotation
  66333. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  66334. }
  66335. }
  66336. };
  66337. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  66338. if (this._mesh) {
  66339. this._mesh.parent = null;
  66340. }
  66341. this._mesh = mesh;
  66342. if (this._poseControlledCamera) {
  66343. this._mesh.parent = this._poseControlledCamera;
  66344. }
  66345. if (!this._mesh.rotationQuaternion) {
  66346. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  66347. }
  66348. };
  66349. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  66350. this._poseControlledCamera = camera;
  66351. if (this._mesh) {
  66352. this._mesh.parent = this._poseControlledCamera;
  66353. }
  66354. };
  66355. PoseEnabledController.prototype.dispose = function () {
  66356. if (this._mesh) {
  66357. this._mesh.dispose();
  66358. }
  66359. this._mesh = null;
  66360. _super.prototype.dispose.call(this);
  66361. };
  66362. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  66363. get: function () {
  66364. return this._mesh;
  66365. },
  66366. enumerable: true,
  66367. configurable: true
  66368. });
  66369. PoseEnabledController.prototype.getForwardRay = function (length) {
  66370. if (length === void 0) { length = 100; }
  66371. if (!this.mesh) {
  66372. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  66373. }
  66374. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  66375. var origin = m.getTranslation();
  66376. var forward = new BABYLON.Vector3(0, 0, -1);
  66377. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  66378. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  66379. return new BABYLON.Ray(origin, direction, length);
  66380. };
  66381. /**
  66382. * Name of the child mesh that can be used to cast a ray from the controller
  66383. */
  66384. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  66385. return PoseEnabledController;
  66386. }(BABYLON.Gamepad));
  66387. BABYLON.PoseEnabledController = PoseEnabledController;
  66388. })(BABYLON || (BABYLON = {}));
  66389. //# sourceMappingURL=babylon.poseEnabledController.js.map
  66390. "use strict";
  66391. var BABYLON;
  66392. (function (BABYLON) {
  66393. var WebVRController = /** @class */ (function (_super) {
  66394. __extends(WebVRController, _super);
  66395. function WebVRController(vrGamepad) {
  66396. var _this = _super.call(this, vrGamepad) || this;
  66397. // Observables
  66398. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  66399. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  66400. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  66401. _this.onPadStateChangedObservable = new BABYLON.Observable();
  66402. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  66403. _this.pad = { x: 0, y: 0 };
  66404. // avoid GC, store state in a tmp object
  66405. _this._changes = {
  66406. pressChanged: false,
  66407. touchChanged: false,
  66408. valueChanged: false,
  66409. changed: false
  66410. };
  66411. _this._buttons = new Array(vrGamepad.buttons.length);
  66412. _this.hand = vrGamepad.hand;
  66413. return _this;
  66414. }
  66415. WebVRController.prototype.onButtonStateChange = function (callback) {
  66416. this._onButtonStateChange = callback;
  66417. };
  66418. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  66419. get: function () {
  66420. return this._defaultModel;
  66421. },
  66422. enumerable: true,
  66423. configurable: true
  66424. });
  66425. WebVRController.prototype.update = function () {
  66426. _super.prototype.update.call(this);
  66427. for (var index = 0; index < this._buttons.length; index++) {
  66428. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  66429. }
  66430. ;
  66431. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  66432. this.pad.x = this.leftStick.x;
  66433. this.pad.y = this.leftStick.y;
  66434. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  66435. }
  66436. };
  66437. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  66438. if (!newState) {
  66439. newState = {
  66440. pressed: false,
  66441. touched: false,
  66442. value: 0
  66443. };
  66444. }
  66445. if (!currentState) {
  66446. this._buttons[buttonIndex] = {
  66447. pressed: newState.pressed,
  66448. touched: newState.touched,
  66449. value: newState.value
  66450. };
  66451. return;
  66452. }
  66453. this._checkChanges(newState, currentState);
  66454. if (this._changes.changed) {
  66455. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  66456. this._handleButtonChange(buttonIndex, newState, this._changes);
  66457. }
  66458. this._buttons[buttonIndex].pressed = newState.pressed;
  66459. this._buttons[buttonIndex].touched = newState.touched;
  66460. // oculus triggers are never 0, thou not touched.
  66461. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  66462. };
  66463. WebVRController.prototype._checkChanges = function (newState, currentState) {
  66464. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  66465. this._changes.touchChanged = newState.touched !== currentState.touched;
  66466. this._changes.valueChanged = newState.value !== currentState.value;
  66467. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  66468. return this._changes;
  66469. };
  66470. WebVRController.prototype.dispose = function () {
  66471. _super.prototype.dispose.call(this);
  66472. this.onTriggerStateChangedObservable.clear();
  66473. this.onMainButtonStateChangedObservable.clear();
  66474. this.onSecondaryButtonStateChangedObservable.clear();
  66475. this.onPadStateChangedObservable.clear();
  66476. this.onPadValuesChangedObservable.clear();
  66477. };
  66478. return WebVRController;
  66479. }(BABYLON.PoseEnabledController));
  66480. BABYLON.WebVRController = WebVRController;
  66481. })(BABYLON || (BABYLON = {}));
  66482. //# sourceMappingURL=babylon.webVRController.js.map
  66483. "use strict";
  66484. var BABYLON;
  66485. (function (BABYLON) {
  66486. var OculusTouchController = /** @class */ (function (_super) {
  66487. __extends(OculusTouchController, _super);
  66488. function OculusTouchController(vrGamepad) {
  66489. var _this = _super.call(this, vrGamepad) || this;
  66490. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  66491. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  66492. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  66493. return _this;
  66494. }
  66495. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66496. var _this = this;
  66497. var meshName;
  66498. // Hand
  66499. if (this.hand === 'left') {
  66500. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  66501. }
  66502. else {
  66503. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  66504. }
  66505. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  66506. /*
  66507. Parent Mesh name: oculus_touch_left
  66508. - body
  66509. - trigger
  66510. - thumbstick
  66511. - grip
  66512. - button_y
  66513. - button_x
  66514. - button_enter
  66515. */
  66516. _this._defaultModel = newMeshes[1];
  66517. _this.attachToMesh(_this._defaultModel);
  66518. if (meshLoaded) {
  66519. meshLoaded(_this._defaultModel);
  66520. }
  66521. });
  66522. };
  66523. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  66524. // helper getters for left and right hand.
  66525. get: function () {
  66526. if (this.hand === 'right') {
  66527. return this.onMainButtonStateChangedObservable;
  66528. }
  66529. else {
  66530. throw new Error('No A button on left hand');
  66531. }
  66532. },
  66533. enumerable: true,
  66534. configurable: true
  66535. });
  66536. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  66537. get: function () {
  66538. if (this.hand === 'right') {
  66539. return this.onSecondaryButtonStateChangedObservable;
  66540. }
  66541. else {
  66542. throw new Error('No B button on left hand');
  66543. }
  66544. },
  66545. enumerable: true,
  66546. configurable: true
  66547. });
  66548. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  66549. get: function () {
  66550. if (this.hand === 'left') {
  66551. return this.onMainButtonStateChangedObservable;
  66552. }
  66553. else {
  66554. throw new Error('No X button on right hand');
  66555. }
  66556. },
  66557. enumerable: true,
  66558. configurable: true
  66559. });
  66560. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  66561. get: function () {
  66562. if (this.hand === 'left') {
  66563. return this.onSecondaryButtonStateChangedObservable;
  66564. }
  66565. else {
  66566. throw new Error('No Y button on right hand');
  66567. }
  66568. },
  66569. enumerable: true,
  66570. configurable: true
  66571. });
  66572. /*
  66573. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  66574. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  66575. 2) secondary trigger (same)
  66576. 3) A (right) X (left), touch, pressed = value
  66577. 4) B / Y
  66578. 5) thumb rest
  66579. */
  66580. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66581. var notifyObject = state; //{ state: state, changes: changes };
  66582. var triggerDirection = this.hand === 'right' ? -1 : 1;
  66583. switch (buttonIdx) {
  66584. case 0:
  66585. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  66586. return;
  66587. case 1:// index trigger
  66588. if (this._defaultModel) {
  66589. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  66590. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  66591. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  66592. }
  66593. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  66594. return;
  66595. case 2:// secondary trigger
  66596. if (this._defaultModel) {
  66597. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  66598. }
  66599. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  66600. return;
  66601. case 3:
  66602. if (this._defaultModel) {
  66603. if (notifyObject.pressed) {
  66604. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  66605. }
  66606. else {
  66607. (this._defaultModel.getChildren()[1]).position.y = 0;
  66608. }
  66609. }
  66610. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  66611. return;
  66612. case 4:
  66613. if (this._defaultModel) {
  66614. if (notifyObject.pressed) {
  66615. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  66616. }
  66617. else {
  66618. (this._defaultModel.getChildren()[2]).position.y = 0;
  66619. }
  66620. }
  66621. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  66622. return;
  66623. case 5:
  66624. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  66625. return;
  66626. }
  66627. };
  66628. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  66629. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  66630. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  66631. return OculusTouchController;
  66632. }(BABYLON.WebVRController));
  66633. BABYLON.OculusTouchController = OculusTouchController;
  66634. })(BABYLON || (BABYLON = {}));
  66635. //# sourceMappingURL=babylon.oculusTouchController.js.map
  66636. "use strict";
  66637. var BABYLON;
  66638. (function (BABYLON) {
  66639. var ViveController = /** @class */ (function (_super) {
  66640. __extends(ViveController, _super);
  66641. function ViveController(vrGamepad) {
  66642. var _this = _super.call(this, vrGamepad) || this;
  66643. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  66644. _this._invertLeftStickY = true;
  66645. return _this;
  66646. }
  66647. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66648. var _this = this;
  66649. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  66650. /*
  66651. Parent Mesh name: ViveWand
  66652. - body
  66653. - r_gripper
  66654. - l_gripper
  66655. - menu_button
  66656. - system_button
  66657. - trackpad
  66658. - trigger
  66659. - LED
  66660. */
  66661. _this._defaultModel = newMeshes[1];
  66662. _this.attachToMesh(_this._defaultModel);
  66663. if (meshLoaded) {
  66664. meshLoaded(_this._defaultModel);
  66665. }
  66666. });
  66667. };
  66668. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  66669. get: function () {
  66670. return this.onMainButtonStateChangedObservable;
  66671. },
  66672. enumerable: true,
  66673. configurable: true
  66674. });
  66675. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  66676. get: function () {
  66677. return this.onMainButtonStateChangedObservable;
  66678. },
  66679. enumerable: true,
  66680. configurable: true
  66681. });
  66682. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  66683. get: function () {
  66684. return this.onSecondaryButtonStateChangedObservable;
  66685. },
  66686. enumerable: true,
  66687. configurable: true
  66688. });
  66689. /**
  66690. * Vive mapping:
  66691. * 0: touchpad
  66692. * 1: trigger
  66693. * 2: left AND right buttons
  66694. * 3: menu button
  66695. */
  66696. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66697. var notifyObject = state; //{ state: state, changes: changes };
  66698. switch (buttonIdx) {
  66699. case 0:
  66700. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  66701. return;
  66702. case 1:// index trigger
  66703. if (this._defaultModel) {
  66704. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  66705. }
  66706. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  66707. return;
  66708. case 2:// left AND right button
  66709. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  66710. return;
  66711. case 3:
  66712. if (this._defaultModel) {
  66713. if (notifyObject.pressed) {
  66714. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  66715. }
  66716. else {
  66717. (this._defaultModel.getChildren()[2]).position.y = 0;
  66718. }
  66719. }
  66720. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  66721. return;
  66722. }
  66723. };
  66724. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  66725. ViveController.MODEL_FILENAME = 'wand.babylon';
  66726. return ViveController;
  66727. }(BABYLON.WebVRController));
  66728. BABYLON.ViveController = ViveController;
  66729. })(BABYLON || (BABYLON = {}));
  66730. //# sourceMappingURL=babylon.viveController.js.map
  66731. "use strict";
  66732. var BABYLON;
  66733. (function (BABYLON) {
  66734. var GenericController = /** @class */ (function (_super) {
  66735. __extends(GenericController, _super);
  66736. function GenericController(vrGamepad) {
  66737. return _super.call(this, vrGamepad) || this;
  66738. }
  66739. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  66740. var _this = this;
  66741. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  66742. _this._defaultModel = newMeshes[1];
  66743. _this.attachToMesh(_this._defaultModel);
  66744. if (meshLoaded) {
  66745. meshLoaded(_this._defaultModel);
  66746. }
  66747. });
  66748. };
  66749. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66750. console.log("Button id: " + buttonIdx + "state: ");
  66751. console.dir(state);
  66752. };
  66753. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  66754. GenericController.MODEL_FILENAME = 'generic.babylon';
  66755. return GenericController;
  66756. }(BABYLON.WebVRController));
  66757. BABYLON.GenericController = GenericController;
  66758. })(BABYLON || (BABYLON = {}));
  66759. //# sourceMappingURL=babylon.genericController.js.map
  66760. "use strict";
  66761. var BABYLON;
  66762. (function (BABYLON) {
  66763. var LoadedMeshInfo = /** @class */ (function () {
  66764. function LoadedMeshInfo() {
  66765. this.buttonMeshes = {};
  66766. this.axisMeshes = {};
  66767. }
  66768. return LoadedMeshInfo;
  66769. }());
  66770. var WindowsMotionController = /** @class */ (function (_super) {
  66771. __extends(WindowsMotionController, _super);
  66772. function WindowsMotionController(vrGamepad) {
  66773. var _this = _super.call(this, vrGamepad) || this;
  66774. _this._mapping = {
  66775. // Semantic button names
  66776. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  66777. // A mapping of the button name to glTF model node name
  66778. // that should be transformed by button value.
  66779. buttonMeshNames: {
  66780. 'trigger': 'SELECT',
  66781. 'menu': 'MENU',
  66782. 'grip': 'GRASP',
  66783. 'thumbstick': 'THUMBSTICK_PRESS',
  66784. 'trackpad': 'TOUCHPAD_PRESS'
  66785. },
  66786. // This mapping is used to translate from the Motion Controller to Babylon semantics
  66787. buttonObservableNames: {
  66788. 'trigger': 'onTriggerStateChangedObservable',
  66789. 'menu': 'onSecondaryButtonStateChangedObservable',
  66790. 'grip': 'onMainButtonStateChangedObservable',
  66791. 'thumbstick': 'onPadStateChangedObservable',
  66792. 'trackpad': 'onTrackpadChangedObservable'
  66793. },
  66794. // A mapping of the axis name to glTF model node name
  66795. // that should be transformed by axis value.
  66796. // This array mirrors the browserGamepad.axes array, such that
  66797. // the mesh corresponding to axis 0 is in this array index 0.
  66798. axisMeshNames: [
  66799. 'THUMBSTICK_X',
  66800. 'THUMBSTICK_Y',
  66801. 'TOUCHPAD_TOUCH_X',
  66802. 'TOUCHPAD_TOUCH_Y'
  66803. ],
  66804. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  66805. };
  66806. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  66807. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  66808. _this.trackpad = { x: 0, y: 0 };
  66809. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  66810. _this._loadedMeshInfo = null;
  66811. return _this;
  66812. }
  66813. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  66814. get: function () {
  66815. return this.onTriggerStateChangedObservable;
  66816. },
  66817. enumerable: true,
  66818. configurable: true
  66819. });
  66820. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  66821. get: function () {
  66822. return this.onSecondaryButtonStateChangedObservable;
  66823. },
  66824. enumerable: true,
  66825. configurable: true
  66826. });
  66827. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  66828. get: function () {
  66829. return this.onMainButtonStateChangedObservable;
  66830. },
  66831. enumerable: true,
  66832. configurable: true
  66833. });
  66834. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  66835. get: function () {
  66836. return this.onPadStateChangedObservable;
  66837. },
  66838. enumerable: true,
  66839. configurable: true
  66840. });
  66841. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  66842. get: function () {
  66843. return this.onTrackpadChangedObservable;
  66844. },
  66845. enumerable: true,
  66846. configurable: true
  66847. });
  66848. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  66849. get: function () {
  66850. return this.onTrackpadValuesChangedObservable;
  66851. },
  66852. enumerable: true,
  66853. configurable: true
  66854. });
  66855. /**
  66856. * Called once per frame by the engine.
  66857. */
  66858. WindowsMotionController.prototype.update = function () {
  66859. _super.prototype.update.call(this);
  66860. if (this.browserGamepad.axes) {
  66861. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  66862. this.trackpad.x = this.browserGamepad["axes"][2];
  66863. this.trackpad.y = this.browserGamepad["axes"][3];
  66864. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  66865. }
  66866. // Only need to animate axes if there is a loaded mesh
  66867. if (this._loadedMeshInfo) {
  66868. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  66869. this.lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  66870. }
  66871. }
  66872. }
  66873. };
  66874. /**
  66875. * Called once for each button that changed state since the last frame
  66876. * @param buttonIdx Which button index changed
  66877. * @param state New state of the button
  66878. * @param changes Which properties on the state changed since last frame
  66879. */
  66880. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  66881. var buttonName = this._mapping.buttons[buttonIdx];
  66882. if (!buttonName) {
  66883. return;
  66884. }
  66885. // Only emit events for buttons that we know how to map from index to name
  66886. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  66887. if (observable) {
  66888. observable.notifyObservers(state);
  66889. }
  66890. this.lerpButtonTransform(buttonName, state.value);
  66891. };
  66892. WindowsMotionController.prototype.lerpButtonTransform = function (buttonName, buttonValue) {
  66893. // If there is no loaded mesh, there is nothing to transform.
  66894. if (!this._loadedMeshInfo) {
  66895. return;
  66896. }
  66897. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  66898. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  66899. return;
  66900. }
  66901. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  66902. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  66903. };
  66904. WindowsMotionController.prototype.lerpAxisTransform = function (axis, axisValue) {
  66905. if (!this._loadedMeshInfo) {
  66906. return;
  66907. }
  66908. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  66909. if (!meshInfo) {
  66910. return;
  66911. }
  66912. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  66913. return;
  66914. }
  66915. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  66916. var lerpValue = axisValue * 0.5 + 0.5;
  66917. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  66918. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  66919. };
  66920. /**
  66921. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  66922. * @param scene scene in which to add meshes
  66923. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  66924. */
  66925. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  66926. var _this = this;
  66927. if (forceDefault === void 0) { forceDefault = false; }
  66928. var path;
  66929. var filename;
  66930. // Checking if GLB loader is present
  66931. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  66932. // Determine the device specific folder based on the ID suffix
  66933. var device = 'default';
  66934. if (this.id && !forceDefault) {
  66935. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  66936. device = ((match && match[0]) || device);
  66937. }
  66938. // Hand
  66939. if (this.hand === 'left') {
  66940. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  66941. }
  66942. else {
  66943. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  66944. }
  66945. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  66946. }
  66947. else {
  66948. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  66949. path = BABYLON.GenericController.MODEL_BASE_URL;
  66950. filename = BABYLON.GenericController.MODEL_FILENAME;
  66951. }
  66952. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  66953. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  66954. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  66955. if (!_this._loadedMeshInfo) {
  66956. return;
  66957. }
  66958. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  66959. _this.attachToMesh(_this._defaultModel);
  66960. if (meshLoaded) {
  66961. meshLoaded(_this._defaultModel);
  66962. }
  66963. }, null, function (scene, message) {
  66964. BABYLON.Tools.Log(message);
  66965. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  66966. if (!forceDefault) {
  66967. _this.initControllerMesh(scene, meshLoaded, true);
  66968. }
  66969. });
  66970. };
  66971. /**
  66972. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  66973. * can be transformed by button presses and axes values, based on this._mapping.
  66974. *
  66975. * @param scene scene in which the meshes exist
  66976. * @param meshes list of meshes that make up the controller model to process
  66977. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  66978. */
  66979. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  66980. var loadedMeshInfo = null;
  66981. // Create a new mesh to contain the glTF hierarchy
  66982. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  66983. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  66984. var childMesh = null;
  66985. for (var i = 0; i < meshes.length; i++) {
  66986. var mesh = meshes[i];
  66987. if (!mesh.parent) {
  66988. // Exclude controller meshes from picking results
  66989. mesh.isPickable = false;
  66990. // Handle root node, attach to the new parentMesh
  66991. childMesh = mesh;
  66992. break;
  66993. }
  66994. }
  66995. if (childMesh) {
  66996. childMesh.setParent(parentMesh);
  66997. // Create our mesh info. Note that this method will always return non-null.
  66998. loadedMeshInfo = this.createMeshInfo(parentMesh);
  66999. }
  67000. else {
  67001. BABYLON.Tools.Warn('Could not find root node in model file.');
  67002. }
  67003. return loadedMeshInfo;
  67004. };
  67005. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  67006. var loadedMeshInfo = new LoadedMeshInfo();
  67007. var i;
  67008. loadedMeshInfo.rootNode = rootNode;
  67009. // Reset the caches
  67010. loadedMeshInfo.buttonMeshes = {};
  67011. loadedMeshInfo.axisMeshes = {};
  67012. // Button Meshes
  67013. for (i = 0; i < this._mapping.buttons.length; i++) {
  67014. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  67015. if (!buttonMeshName) {
  67016. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  67017. continue;
  67018. }
  67019. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  67020. if (!buttonMesh) {
  67021. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  67022. continue;
  67023. }
  67024. var buttonMeshInfo = {
  67025. index: i,
  67026. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  67027. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  67028. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  67029. };
  67030. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  67031. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  67032. }
  67033. else {
  67034. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  67035. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  67036. '(VALUE: ' + !!buttonMeshInfo.value +
  67037. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  67038. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  67039. ')');
  67040. }
  67041. }
  67042. // Axis Meshes
  67043. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  67044. var axisMeshName = this._mapping.axisMeshNames[i];
  67045. if (!axisMeshName) {
  67046. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  67047. continue;
  67048. }
  67049. var axisMesh = getChildByName(rootNode, axisMeshName);
  67050. if (!axisMesh) {
  67051. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  67052. continue;
  67053. }
  67054. var axisMeshInfo = {
  67055. index: i,
  67056. value: getImmediateChildByName(axisMesh, 'VALUE'),
  67057. min: getImmediateChildByName(axisMesh, 'MIN'),
  67058. max: getImmediateChildByName(axisMesh, 'MAX')
  67059. };
  67060. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  67061. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  67062. }
  67063. else {
  67064. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  67065. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  67066. '(VALUE: ' + !!axisMeshInfo.value +
  67067. ', MIN: ' + !!axisMeshInfo.min +
  67068. ', MAX:' + !!axisMeshInfo.max +
  67069. ')');
  67070. }
  67071. }
  67072. // Pointing Ray
  67073. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  67074. if (!loadedMeshInfo.pointingPoseNode) {
  67075. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  67076. }
  67077. return loadedMeshInfo;
  67078. // Look through all children recursively. This will return null if no mesh exists with the given name.
  67079. function getChildByName(node, name) {
  67080. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  67081. }
  67082. // Look through only immediate children. This will return null if no mesh exists with the given name.
  67083. function getImmediateChildByName(node, name) {
  67084. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  67085. }
  67086. };
  67087. WindowsMotionController.prototype.getForwardRay = function (length) {
  67088. if (length === void 0) { length = 100; }
  67089. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  67090. return _super.prototype.getForwardRay.call(this, length);
  67091. }
  67092. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  67093. var origin = m.getTranslation();
  67094. var forward = new BABYLON.Vector3(0, 0, -1);
  67095. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  67096. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  67097. return new BABYLON.Ray(origin, direction, length);
  67098. };
  67099. WindowsMotionController.prototype.dispose = function () {
  67100. _super.prototype.dispose.call(this);
  67101. this.onTrackpadChangedObservable.clear();
  67102. };
  67103. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  67104. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  67105. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  67106. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  67107. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  67108. return WindowsMotionController;
  67109. }(BABYLON.WebVRController));
  67110. BABYLON.WindowsMotionController = WindowsMotionController;
  67111. })(BABYLON || (BABYLON = {}));
  67112. //# sourceMappingURL=babylon.windowsMotionController.js.map
  67113. "use strict";
  67114. var BABYLON;
  67115. (function (BABYLON) {
  67116. var GearVRController = /** @class */ (function (_super) {
  67117. __extends(GearVRController, _super);
  67118. function GearVRController(vrGamepad) {
  67119. var _this = _super.call(this, vrGamepad) || this;
  67120. _this._buttonIndexToObservableNameMap = [
  67121. 'onTrackpadChangedObservable',
  67122. 'onTriggerStateChangedObservable' // Trigger
  67123. ];
  67124. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  67125. return _this;
  67126. }
  67127. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  67128. var _this = this;
  67129. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  67130. _this._defaultModel = newMeshes[1];
  67131. _this.attachToMesh(_this._defaultModel);
  67132. if (meshLoaded) {
  67133. meshLoaded(_this._defaultModel);
  67134. }
  67135. });
  67136. };
  67137. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  67138. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  67139. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  67140. // Only emit events for buttons that we know how to map from index to observable
  67141. var observable = this[observableName];
  67142. if (observable) {
  67143. observable.notifyObservers(state);
  67144. }
  67145. }
  67146. };
  67147. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  67148. GearVRController.MODEL_FILENAME = 'generic.babylon';
  67149. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  67150. return GearVRController;
  67151. }(BABYLON.WebVRController));
  67152. BABYLON.GearVRController = GearVRController;
  67153. })(BABYLON || (BABYLON = {}));
  67154. //# sourceMappingURL=babylon.gearVRController.js.map
  67155. "use strict";
  67156. var BABYLON;
  67157. (function (BABYLON) {
  67158. /**
  67159. * Google Daydream controller
  67160. */
  67161. var DaydreamController = /** @class */ (function (_super) {
  67162. __extends(DaydreamController, _super);
  67163. function DaydreamController(vrGamepad) {
  67164. var _this = _super.call(this, vrGamepad) || this;
  67165. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  67166. return _this;
  67167. }
  67168. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  67169. var _this = this;
  67170. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  67171. _this._defaultModel = newMeshes[1];
  67172. _this.attachToMesh(_this._defaultModel);
  67173. if (meshLoaded) {
  67174. meshLoaded(_this._defaultModel);
  67175. }
  67176. });
  67177. };
  67178. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  67179. // Daydream controller only has 1 GamepadButton (on the trackpad).
  67180. if (buttonIdx === 0) {
  67181. var observable = this.onTriggerStateChangedObservable;
  67182. if (observable) {
  67183. observable.notifyObservers(state);
  67184. }
  67185. }
  67186. else {
  67187. // If the app or home buttons are ever made available
  67188. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  67189. }
  67190. };
  67191. /**
  67192. * Base Url for the controller model.
  67193. */
  67194. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  67195. /**
  67196. * File name for the controller model.
  67197. */
  67198. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  67199. /**
  67200. * Gamepad Id prefix used to identify Daydream Controller.
  67201. */
  67202. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  67203. return DaydreamController;
  67204. }(BABYLON.WebVRController));
  67205. BABYLON.DaydreamController = DaydreamController;
  67206. })(BABYLON || (BABYLON = {}));
  67207. //# sourceMappingURL=babylon.daydreamController.js.map
  67208. "use strict";
  67209. var BABYLON;
  67210. (function (BABYLON) {
  67211. var FollowCamera = /** @class */ (function (_super) {
  67212. __extends(FollowCamera, _super);
  67213. function FollowCamera(name, position, scene, lockedTarget) {
  67214. if (lockedTarget === void 0) { lockedTarget = null; }
  67215. var _this = _super.call(this, name, position, scene) || this;
  67216. _this.radius = 12;
  67217. _this.rotationOffset = 0;
  67218. _this.heightOffset = 4;
  67219. _this.cameraAcceleration = 0.05;
  67220. _this.maxCameraSpeed = 20;
  67221. _this.lockedTarget = lockedTarget;
  67222. return _this;
  67223. }
  67224. FollowCamera.prototype.getRadians = function (degrees) {
  67225. return degrees * Math.PI / 180;
  67226. };
  67227. FollowCamera.prototype.follow = function (cameraTarget) {
  67228. if (!cameraTarget)
  67229. return;
  67230. var yRotation;
  67231. if (cameraTarget.rotationQuaternion) {
  67232. var rotMatrix = new BABYLON.Matrix();
  67233. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  67234. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  67235. }
  67236. else {
  67237. yRotation = cameraTarget.rotation.y;
  67238. }
  67239. var radians = this.getRadians(this.rotationOffset) + yRotation;
  67240. var targetPosition = cameraTarget.getAbsolutePosition();
  67241. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  67242. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  67243. var dx = targetX - this.position.x;
  67244. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  67245. var dz = (targetZ) - this.position.z;
  67246. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  67247. var vy = dy * this.cameraAcceleration;
  67248. var vz = dz * this.cameraAcceleration * 2;
  67249. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  67250. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  67251. }
  67252. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  67253. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  67254. }
  67255. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  67256. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  67257. }
  67258. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  67259. this.setTarget(targetPosition);
  67260. };
  67261. FollowCamera.prototype._checkInputs = function () {
  67262. _super.prototype._checkInputs.call(this);
  67263. if (this.lockedTarget) {
  67264. this.follow(this.lockedTarget);
  67265. }
  67266. };
  67267. FollowCamera.prototype.getClassName = function () {
  67268. return "FollowCamera";
  67269. };
  67270. __decorate([
  67271. BABYLON.serialize()
  67272. ], FollowCamera.prototype, "radius", void 0);
  67273. __decorate([
  67274. BABYLON.serialize()
  67275. ], FollowCamera.prototype, "rotationOffset", void 0);
  67276. __decorate([
  67277. BABYLON.serialize()
  67278. ], FollowCamera.prototype, "heightOffset", void 0);
  67279. __decorate([
  67280. BABYLON.serialize()
  67281. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  67282. __decorate([
  67283. BABYLON.serialize()
  67284. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  67285. __decorate([
  67286. BABYLON.serializeAsMeshReference("lockedTargetId")
  67287. ], FollowCamera.prototype, "lockedTarget", void 0);
  67288. return FollowCamera;
  67289. }(BABYLON.TargetCamera));
  67290. BABYLON.FollowCamera = FollowCamera;
  67291. var ArcFollowCamera = /** @class */ (function (_super) {
  67292. __extends(ArcFollowCamera, _super);
  67293. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  67294. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  67295. _this.alpha = alpha;
  67296. _this.beta = beta;
  67297. _this.radius = radius;
  67298. _this.target = target;
  67299. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  67300. _this.follow();
  67301. return _this;
  67302. }
  67303. ArcFollowCamera.prototype.follow = function () {
  67304. if (!this.target) {
  67305. return;
  67306. }
  67307. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  67308. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  67309. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  67310. var targetPosition = this.target.getAbsolutePosition();
  67311. this.position = targetPosition.add(this._cartesianCoordinates);
  67312. this.setTarget(targetPosition);
  67313. };
  67314. ArcFollowCamera.prototype._checkInputs = function () {
  67315. _super.prototype._checkInputs.call(this);
  67316. this.follow();
  67317. };
  67318. ArcFollowCamera.prototype.getClassName = function () {
  67319. return "ArcFollowCamera";
  67320. };
  67321. return ArcFollowCamera;
  67322. }(BABYLON.TargetCamera));
  67323. BABYLON.ArcFollowCamera = ArcFollowCamera;
  67324. })(BABYLON || (BABYLON = {}));
  67325. //# sourceMappingURL=babylon.followCamera.js.map
  67326. "use strict";
  67327. var BABYLON;
  67328. (function (BABYLON) {
  67329. // We're mainly based on the logic defined into the FreeCamera code
  67330. var UniversalCamera = /** @class */ (function (_super) {
  67331. __extends(UniversalCamera, _super);
  67332. //-- end properties for backward compatibility for inputs
  67333. function UniversalCamera(name, position, scene) {
  67334. var _this = _super.call(this, name, position, scene) || this;
  67335. _this.inputs.addGamepad();
  67336. return _this;
  67337. }
  67338. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  67339. //-- Begin properties for backward compatibility for inputs
  67340. get: function () {
  67341. var gamepad = this.inputs.attached["gamepad"];
  67342. if (gamepad)
  67343. return gamepad.gamepadAngularSensibility;
  67344. return 0;
  67345. },
  67346. set: function (value) {
  67347. var gamepad = this.inputs.attached["gamepad"];
  67348. if (gamepad)
  67349. gamepad.gamepadAngularSensibility = value;
  67350. },
  67351. enumerable: true,
  67352. configurable: true
  67353. });
  67354. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  67355. get: function () {
  67356. var gamepad = this.inputs.attached["gamepad"];
  67357. if (gamepad)
  67358. return gamepad.gamepadMoveSensibility;
  67359. return 0;
  67360. },
  67361. set: function (value) {
  67362. var gamepad = this.inputs.attached["gamepad"];
  67363. if (gamepad)
  67364. gamepad.gamepadMoveSensibility = value;
  67365. },
  67366. enumerable: true,
  67367. configurable: true
  67368. });
  67369. UniversalCamera.prototype.getClassName = function () {
  67370. return "UniversalCamera";
  67371. };
  67372. return UniversalCamera;
  67373. }(BABYLON.TouchCamera));
  67374. BABYLON.UniversalCamera = UniversalCamera;
  67375. })(BABYLON || (BABYLON = {}));
  67376. //# sourceMappingURL=babylon.universalCamera.js.map
  67377. "use strict";
  67378. var BABYLON;
  67379. (function (BABYLON) {
  67380. // We're mainly based on the logic defined into the FreeCamera code
  67381. var GamepadCamera = /** @class */ (function (_super) {
  67382. __extends(GamepadCamera, _super);
  67383. //-- end properties for backward compatibility for inputs
  67384. function GamepadCamera(name, position, scene) {
  67385. return _super.call(this, name, position, scene) || this;
  67386. }
  67387. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  67388. //-- Begin properties for backward compatibility for inputs
  67389. get: function () {
  67390. var gamepad = this.inputs.attached["gamepad"];
  67391. if (gamepad)
  67392. return gamepad.gamepadAngularSensibility;
  67393. return 0;
  67394. },
  67395. set: function (value) {
  67396. var gamepad = this.inputs.attached["gamepad"];
  67397. if (gamepad)
  67398. gamepad.gamepadAngularSensibility = value;
  67399. },
  67400. enumerable: true,
  67401. configurable: true
  67402. });
  67403. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  67404. get: function () {
  67405. var gamepad = this.inputs.attached["gamepad"];
  67406. if (gamepad)
  67407. return gamepad.gamepadMoveSensibility;
  67408. return 0;
  67409. },
  67410. set: function (value) {
  67411. var gamepad = this.inputs.attached["gamepad"];
  67412. if (gamepad)
  67413. gamepad.gamepadMoveSensibility = value;
  67414. },
  67415. enumerable: true,
  67416. configurable: true
  67417. });
  67418. GamepadCamera.prototype.getClassName = function () {
  67419. return "GamepadCamera";
  67420. };
  67421. return GamepadCamera;
  67422. }(BABYLON.UniversalCamera));
  67423. BABYLON.GamepadCamera = GamepadCamera;
  67424. })(BABYLON || (BABYLON = {}));
  67425. //# sourceMappingURL=babylon.gamepadCamera.js.map
  67426. "use strict";
  67427. var BABYLON;
  67428. (function (BABYLON) {
  67429. var PostProcessRenderPipelineManager = /** @class */ (function () {
  67430. function PostProcessRenderPipelineManager() {
  67431. this._renderPipelines = {};
  67432. }
  67433. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  67434. this._renderPipelines[renderPipeline._name] = renderPipeline;
  67435. };
  67436. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  67437. if (unique === void 0) { unique = false; }
  67438. var renderPipeline = this._renderPipelines[renderPipelineName];
  67439. if (!renderPipeline) {
  67440. return;
  67441. }
  67442. renderPipeline._attachCameras(cameras, unique);
  67443. };
  67444. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  67445. var renderPipeline = this._renderPipelines[renderPipelineName];
  67446. if (!renderPipeline) {
  67447. return;
  67448. }
  67449. renderPipeline._detachCameras(cameras);
  67450. };
  67451. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  67452. var renderPipeline = this._renderPipelines[renderPipelineName];
  67453. if (!renderPipeline) {
  67454. return;
  67455. }
  67456. renderPipeline._enableEffect(renderEffectName, cameras);
  67457. };
  67458. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  67459. var renderPipeline = this._renderPipelines[renderPipelineName];
  67460. if (!renderPipeline) {
  67461. return;
  67462. }
  67463. renderPipeline._disableEffect(renderEffectName, cameras);
  67464. };
  67465. PostProcessRenderPipelineManager.prototype.update = function () {
  67466. for (var renderPipelineName in this._renderPipelines) {
  67467. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  67468. var pipeline = this._renderPipelines[renderPipelineName];
  67469. if (!pipeline.isSupported) {
  67470. pipeline.dispose();
  67471. delete this._renderPipelines[renderPipelineName];
  67472. }
  67473. else {
  67474. pipeline._update();
  67475. }
  67476. }
  67477. }
  67478. };
  67479. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  67480. for (var renderPipelineName in this._renderPipelines) {
  67481. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  67482. var pipeline = this._renderPipelines[renderPipelineName];
  67483. pipeline._rebuild();
  67484. }
  67485. }
  67486. };
  67487. PostProcessRenderPipelineManager.prototype.dispose = function () {
  67488. for (var renderPipelineName in this._renderPipelines) {
  67489. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  67490. var pipeline = this._renderPipelines[renderPipelineName];
  67491. pipeline.dispose();
  67492. }
  67493. }
  67494. };
  67495. return PostProcessRenderPipelineManager;
  67496. }());
  67497. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  67498. })(BABYLON || (BABYLON = {}));
  67499. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  67500. "use strict";
  67501. var BABYLON;
  67502. (function (BABYLON) {
  67503. /**
  67504. * This represents a set of one or more post processes in Babylon.
  67505. * A post process can be used to apply a shader to a texture after it is rendered.
  67506. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  67507. */
  67508. var PostProcessRenderEffect = /** @class */ (function () {
  67509. /**
  67510. * Instantiates a post process render effect.
  67511. * A post process can be used to apply a shader to a texture after it is rendered.
  67512. * @param engine The engine the effect is tied to
  67513. * @param name The name of the effect
  67514. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  67515. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  67516. */
  67517. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  67518. this._name = name;
  67519. this._singleInstance = singleInstance || true;
  67520. this._getPostProcesses = getPostProcesses;
  67521. this._cameras = {};
  67522. this._indicesForCamera = {};
  67523. this._postProcesses = {};
  67524. }
  67525. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  67526. /**
  67527. * Checks if all the post processes in the effect are supported.
  67528. */
  67529. get: function () {
  67530. for (var index in this._postProcesses) {
  67531. for (var ppIndex in this._postProcesses[index]) {
  67532. if (!this._postProcesses[index][ppIndex].isSupported) {
  67533. return false;
  67534. }
  67535. }
  67536. }
  67537. return true;
  67538. },
  67539. enumerable: true,
  67540. configurable: true
  67541. });
  67542. /**
  67543. * Updates the current state of the effect
  67544. */
  67545. PostProcessRenderEffect.prototype._update = function () {
  67546. };
  67547. /**
  67548. * Attaches the effect on cameras
  67549. * @param cameras The camera to attach to.
  67550. */
  67551. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  67552. var _this = this;
  67553. var cameraKey;
  67554. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67555. if (!cams) {
  67556. return;
  67557. }
  67558. for (var i = 0; i < cams.length; i++) {
  67559. var camera = cams[i];
  67560. var cameraName = camera.name;
  67561. if (this._singleInstance) {
  67562. cameraKey = 0;
  67563. }
  67564. else {
  67565. cameraKey = cameraName;
  67566. }
  67567. if (!this._postProcesses[cameraKey]) {
  67568. var postProcess = this._getPostProcesses();
  67569. if (postProcess) {
  67570. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  67571. }
  67572. }
  67573. if (!this._indicesForCamera[cameraName]) {
  67574. this._indicesForCamera[cameraName] = [];
  67575. }
  67576. this._postProcesses[cameraKey].forEach(function (postProcess) {
  67577. var index = camera.attachPostProcess(postProcess);
  67578. _this._indicesForCamera[cameraName].push(index);
  67579. });
  67580. if (!this._cameras[cameraName]) {
  67581. this._cameras[cameraName] = camera;
  67582. }
  67583. }
  67584. };
  67585. /**
  67586. * Detatches the effect on cameras
  67587. * @param cameras The camera to detatch from.
  67588. */
  67589. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  67590. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67591. if (!cams) {
  67592. return;
  67593. }
  67594. for (var i = 0; i < cams.length; i++) {
  67595. var camera = cams[i];
  67596. var cameraName = camera.name;
  67597. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  67598. camera.detachPostProcess(postProcess);
  67599. });
  67600. if (this._cameras[cameraName]) {
  67601. //this._indicesForCamera.splice(index, 1);
  67602. this._cameras[cameraName] = null;
  67603. }
  67604. }
  67605. };
  67606. /**
  67607. * Enables the effect on given cameras
  67608. * @param cameras The camera to enable.
  67609. */
  67610. PostProcessRenderEffect.prototype._enable = function (cameras) {
  67611. var _this = this;
  67612. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67613. if (!cams) {
  67614. return;
  67615. }
  67616. for (var i = 0; i < cams.length; i++) {
  67617. var camera = cams[i];
  67618. var cameraName = camera.name;
  67619. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  67620. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  67621. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  67622. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  67623. });
  67624. }
  67625. }
  67626. }
  67627. };
  67628. /**
  67629. * Disables the effect on the given cameras
  67630. * @param cameras The camera to disable.
  67631. */
  67632. PostProcessRenderEffect.prototype._disable = function (cameras) {
  67633. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67634. if (!cams) {
  67635. return;
  67636. }
  67637. for (var i = 0; i < cams.length; i++) {
  67638. var camera = cams[i];
  67639. var cameraName = camera.name;
  67640. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  67641. camera.detachPostProcess(postProcess);
  67642. });
  67643. }
  67644. };
  67645. /**
  67646. * Gets a list of the post processes contained in the effect.
  67647. * @param camera The camera to get the post processes on.
  67648. * @returns The list of the post processes in the effect.
  67649. */
  67650. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  67651. if (this._singleInstance) {
  67652. return this._postProcesses[0];
  67653. }
  67654. else {
  67655. if (!camera) {
  67656. return null;
  67657. }
  67658. return this._postProcesses[camera.name];
  67659. }
  67660. };
  67661. return PostProcessRenderEffect;
  67662. }());
  67663. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  67664. })(BABYLON || (BABYLON = {}));
  67665. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  67666. "use strict";
  67667. var BABYLON;
  67668. (function (BABYLON) {
  67669. var PostProcessRenderPipeline = /** @class */ (function () {
  67670. function PostProcessRenderPipeline(engine, name) {
  67671. this.engine = engine;
  67672. this._name = name;
  67673. this._renderEffects = {};
  67674. this._renderEffectsForIsolatedPass = new Array();
  67675. this._cameras = [];
  67676. }
  67677. PostProcessRenderPipeline.prototype.getClassName = function () {
  67678. return "PostProcessRenderPipeline";
  67679. };
  67680. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  67681. get: function () {
  67682. for (var renderEffectName in this._renderEffects) {
  67683. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  67684. if (!this._renderEffects[renderEffectName].isSupported) {
  67685. return false;
  67686. }
  67687. }
  67688. }
  67689. return true;
  67690. },
  67691. enumerable: true,
  67692. configurable: true
  67693. });
  67694. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  67695. this._renderEffects[renderEffect._name] = renderEffect;
  67696. };
  67697. // private
  67698. PostProcessRenderPipeline.prototype._rebuild = function () {
  67699. };
  67700. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  67701. var renderEffects = this._renderEffects[renderEffectName];
  67702. if (!renderEffects) {
  67703. return;
  67704. }
  67705. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  67706. };
  67707. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  67708. var renderEffects = this._renderEffects[renderEffectName];
  67709. if (!renderEffects) {
  67710. return;
  67711. }
  67712. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  67713. };
  67714. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  67715. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67716. if (!cams) {
  67717. return;
  67718. }
  67719. var indicesToDelete = [];
  67720. var i;
  67721. for (i = 0; i < cams.length; i++) {
  67722. var camera = cams[i];
  67723. var cameraName = camera.name;
  67724. if (this._cameras.indexOf(camera) === -1) {
  67725. this._cameras[cameraName] = camera;
  67726. }
  67727. else if (unique) {
  67728. indicesToDelete.push(i);
  67729. }
  67730. }
  67731. for (i = 0; i < indicesToDelete.length; i++) {
  67732. cameras.splice(indicesToDelete[i], 1);
  67733. }
  67734. for (var renderEffectName in this._renderEffects) {
  67735. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  67736. this._renderEffects[renderEffectName]._attachCameras(cams);
  67737. }
  67738. }
  67739. };
  67740. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  67741. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  67742. if (!cams) {
  67743. return;
  67744. }
  67745. for (var renderEffectName in this._renderEffects) {
  67746. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  67747. this._renderEffects[renderEffectName]._detachCameras(cams);
  67748. }
  67749. }
  67750. for (var i = 0; i < cams.length; i++) {
  67751. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  67752. }
  67753. };
  67754. PostProcessRenderPipeline.prototype._update = function () {
  67755. for (var renderEffectName in this._renderEffects) {
  67756. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  67757. this._renderEffects[renderEffectName]._update();
  67758. }
  67759. }
  67760. for (var i = 0; i < this._cameras.length; i++) {
  67761. var cameraName = this._cameras[i].name;
  67762. if (this._renderEffectsForIsolatedPass[cameraName]) {
  67763. this._renderEffectsForIsolatedPass[cameraName]._update();
  67764. }
  67765. }
  67766. };
  67767. PostProcessRenderPipeline.prototype._reset = function () {
  67768. this._renderEffects = {};
  67769. this._renderEffectsForIsolatedPass = new Array();
  67770. };
  67771. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function () {
  67772. // 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)
  67773. var effectKeys = Object.keys(this._renderEffects);
  67774. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  67775. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  67776. if (postProcesses) {
  67777. postProcesses[0].samples = 4;
  67778. return true;
  67779. }
  67780. }
  67781. return false;
  67782. };
  67783. PostProcessRenderPipeline.prototype.dispose = function () {
  67784. // Must be implemented by children
  67785. };
  67786. __decorate([
  67787. BABYLON.serialize()
  67788. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  67789. return PostProcessRenderPipeline;
  67790. }());
  67791. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  67792. })(BABYLON || (BABYLON = {}));
  67793. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  67794. "use strict";
  67795. var BABYLON;
  67796. (function (BABYLON) {
  67797. /**
  67798. * This represents a depth renderer in Babylon.
  67799. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  67800. */
  67801. var DepthRenderer = /** @class */ (function () {
  67802. /**
  67803. * Instantiates a depth renderer
  67804. * @param scene The scene the renderer belongs to
  67805. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  67806. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  67807. */
  67808. function DepthRenderer(scene, type, camera) {
  67809. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  67810. if (camera === void 0) { camera = null; }
  67811. var _this = this;
  67812. this._scene = scene;
  67813. this._camera = camera;
  67814. var engine = scene.getEngine();
  67815. // Render target
  67816. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  67817. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67818. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67819. this._depthMap.refreshRate = 1;
  67820. this._depthMap.renderParticles = false;
  67821. this._depthMap.renderList = null;
  67822. // Camera to get depth map from to support multiple concurrent cameras
  67823. this._depthMap.activeCamera = this._camera;
  67824. this._depthMap.ignoreCameraViewport = true;
  67825. this._depthMap.useCameraPostProcesses = false;
  67826. // set default depth value to 1.0 (far away)
  67827. this._depthMap.onClearObservable.add(function (engine) {
  67828. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  67829. });
  67830. // Custom render function
  67831. var renderSubMesh = function (subMesh) {
  67832. var mesh = subMesh.getRenderingMesh();
  67833. var scene = _this._scene;
  67834. var engine = scene.getEngine();
  67835. var material = subMesh.getMaterial();
  67836. if (!material) {
  67837. return;
  67838. }
  67839. // Culling and reverse (right handed system)
  67840. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  67841. // Managing instances
  67842. var batch = mesh._getInstancesRenderList(subMesh._id);
  67843. if (batch.mustReturn) {
  67844. return;
  67845. }
  67846. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  67847. var camera = _this._camera || scene.activeCamera;
  67848. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  67849. engine.enableEffect(_this._effect);
  67850. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  67851. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  67852. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  67853. // Alpha test
  67854. if (material && material.needAlphaTesting()) {
  67855. var alphaTexture = material.getAlphaTestTexture();
  67856. if (alphaTexture) {
  67857. _this._effect.setTexture("diffuseSampler", alphaTexture);
  67858. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  67859. }
  67860. }
  67861. // Bones
  67862. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  67863. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  67864. }
  67865. // Draw
  67866. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  67867. }
  67868. };
  67869. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  67870. var index;
  67871. if (depthOnlySubMeshes.length) {
  67872. engine.setColorWrite(false);
  67873. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  67874. renderSubMesh(depthOnlySubMeshes.data[index]);
  67875. }
  67876. engine.setColorWrite(true);
  67877. }
  67878. for (index = 0; index < opaqueSubMeshes.length; index++) {
  67879. renderSubMesh(opaqueSubMeshes.data[index]);
  67880. }
  67881. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  67882. renderSubMesh(alphaTestSubMeshes.data[index]);
  67883. }
  67884. };
  67885. }
  67886. /**
  67887. * Creates the depth rendering effect and checks if the effect is ready.
  67888. * @param subMesh The submesh to be used to render the depth map of
  67889. * @param useInstances If multiple world instances should be used
  67890. * @returns if the depth renderer is ready to render the depth map
  67891. */
  67892. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  67893. var material = subMesh.getMaterial();
  67894. if (material.disableDepthWrite) {
  67895. return false;
  67896. }
  67897. var defines = [];
  67898. var attribs = [BABYLON.VertexBuffer.PositionKind];
  67899. var mesh = subMesh.getMesh();
  67900. // Alpha test
  67901. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  67902. defines.push("#define ALPHATEST");
  67903. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  67904. attribs.push(BABYLON.VertexBuffer.UVKind);
  67905. defines.push("#define UV1");
  67906. }
  67907. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  67908. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  67909. defines.push("#define UV2");
  67910. }
  67911. }
  67912. // Bones
  67913. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  67914. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  67915. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  67916. if (mesh.numBoneInfluencers > 4) {
  67917. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  67918. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  67919. }
  67920. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  67921. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  67922. }
  67923. else {
  67924. defines.push("#define NUM_BONE_INFLUENCERS 0");
  67925. }
  67926. // Instances
  67927. if (useInstances) {
  67928. defines.push("#define INSTANCES");
  67929. attribs.push("world0");
  67930. attribs.push("world1");
  67931. attribs.push("world2");
  67932. attribs.push("world3");
  67933. }
  67934. // Get correct effect
  67935. var join = defines.join("\n");
  67936. if (this._cachedDefines !== join) {
  67937. this._cachedDefines = join;
  67938. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  67939. }
  67940. return this._effect.isReady();
  67941. };
  67942. /**
  67943. * Gets the texture which the depth map will be written to.
  67944. * @returns The depth map texture
  67945. */
  67946. DepthRenderer.prototype.getDepthMap = function () {
  67947. return this._depthMap;
  67948. };
  67949. /**
  67950. * Disposes of the depth renderer.
  67951. */
  67952. DepthRenderer.prototype.dispose = function () {
  67953. this._depthMap.dispose();
  67954. };
  67955. return DepthRenderer;
  67956. }());
  67957. BABYLON.DepthRenderer = DepthRenderer;
  67958. })(BABYLON || (BABYLON = {}));
  67959. //# sourceMappingURL=babylon.depthRenderer.js.map
  67960. "use strict";
  67961. var BABYLON;
  67962. (function (BABYLON) {
  67963. var SSAORenderingPipeline = /** @class */ (function (_super) {
  67964. __extends(SSAORenderingPipeline, _super);
  67965. /**
  67966. * @constructor
  67967. * @param {string} name - The rendering pipeline name
  67968. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  67969. * @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 }
  67970. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  67971. */
  67972. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  67973. var _this = _super.call(this, scene.getEngine(), name) || this;
  67974. // Members
  67975. /**
  67976. * The PassPostProcess id in the pipeline that contains the original scene color
  67977. * @type {string}
  67978. */
  67979. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  67980. /**
  67981. * The SSAO PostProcess id in the pipeline
  67982. * @type {string}
  67983. */
  67984. _this.SSAORenderEffect = "SSAORenderEffect";
  67985. /**
  67986. * The horizontal blur PostProcess id in the pipeline
  67987. * @type {string}
  67988. */
  67989. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  67990. /**
  67991. * The vertical blur PostProcess id in the pipeline
  67992. * @type {string}
  67993. */
  67994. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  67995. /**
  67996. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  67997. * @type {string}
  67998. */
  67999. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  68000. /**
  68001. * The output strength of the SSAO post-process. Default value is 1.0.
  68002. * @type {number}
  68003. */
  68004. _this.totalStrength = 1.0;
  68005. /**
  68006. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  68007. * @type {number}
  68008. */
  68009. _this.radius = 0.0001;
  68010. /**
  68011. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  68012. * Must not be equal to fallOff and superior to fallOff.
  68013. * Default value is 0.975
  68014. * @type {number}
  68015. */
  68016. _this.area = 0.0075;
  68017. /**
  68018. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  68019. * Must not be equal to area and inferior to area.
  68020. * Default value is 0.0
  68021. * @type {number}
  68022. */
  68023. _this.fallOff = 0.000001;
  68024. /**
  68025. * The base color of the SSAO post-process
  68026. * The final result is "base + ssao" between [0, 1]
  68027. * @type {number}
  68028. */
  68029. _this.base = 0.5;
  68030. _this._firstUpdate = true;
  68031. _this._scene = scene;
  68032. // Set up assets
  68033. _this._createRandomTexture();
  68034. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  68035. var ssaoRatio = ratio.ssaoRatio || ratio;
  68036. var combineRatio = ratio.combineRatio || ratio;
  68037. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  68038. _this._createSSAOPostProcess(ssaoRatio);
  68039. _this._createBlurPostProcess(ssaoRatio);
  68040. _this._createSSAOCombinePostProcess(combineRatio);
  68041. // Set up pipeline
  68042. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  68043. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  68044. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  68045. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  68046. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  68047. // Finish
  68048. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68049. if (cameras)
  68050. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  68051. return _this;
  68052. }
  68053. // Public Methods
  68054. /**
  68055. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  68056. */
  68057. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  68058. if (disableDepthRender === void 0) { disableDepthRender = false; }
  68059. for (var i = 0; i < this._scene.cameras.length; i++) {
  68060. var camera = this._scene.cameras[i];
  68061. this._originalColorPostProcess.dispose(camera);
  68062. this._ssaoPostProcess.dispose(camera);
  68063. this._blurHPostProcess.dispose(camera);
  68064. this._blurVPostProcess.dispose(camera);
  68065. this._ssaoCombinePostProcess.dispose(camera);
  68066. }
  68067. this._randomTexture.dispose();
  68068. if (disableDepthRender)
  68069. this._scene.disableDepthRenderer();
  68070. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  68071. _super.prototype.dispose.call(this);
  68072. };
  68073. // Private Methods
  68074. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  68075. var _this = this;
  68076. var size = 16;
  68077. 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);
  68078. 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);
  68079. this._blurHPostProcess.onActivateObservable.add(function () {
  68080. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  68081. _this._blurHPostProcess.kernel = size * dw;
  68082. });
  68083. this._blurVPostProcess.onActivateObservable.add(function () {
  68084. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  68085. _this._blurVPostProcess.kernel = size * dw;
  68086. });
  68087. };
  68088. SSAORenderingPipeline.prototype._rebuild = function () {
  68089. this._firstUpdate = true;
  68090. _super.prototype._rebuild.call(this);
  68091. };
  68092. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  68093. var _this = this;
  68094. var numSamples = 16;
  68095. var sampleSphere = [
  68096. 0.5381, 0.1856, -0.4319,
  68097. 0.1379, 0.2486, 0.4430,
  68098. 0.3371, 0.5679, -0.0057,
  68099. -0.6999, -0.0451, -0.0019,
  68100. 0.0689, -0.1598, -0.8547,
  68101. 0.0560, 0.0069, -0.1843,
  68102. -0.0146, 0.1402, 0.0762,
  68103. 0.0100, -0.1924, -0.0344,
  68104. -0.3577, -0.5301, -0.4358,
  68105. -0.3169, 0.1063, 0.0158,
  68106. 0.0103, -0.5869, 0.0046,
  68107. -0.0897, -0.4940, 0.3287,
  68108. 0.7119, -0.0154, -0.0918,
  68109. -0.0533, 0.0596, -0.5411,
  68110. 0.0352, -0.0631, 0.5460,
  68111. -0.4776, 0.2847, -0.0271
  68112. ];
  68113. var samplesFactor = 1.0 / numSamples;
  68114. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  68115. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  68116. "area", "fallOff", "base", "range", "viewport"
  68117. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  68118. this._ssaoPostProcess.onApply = function (effect) {
  68119. if (_this._firstUpdate) {
  68120. effect.setArray3("sampleSphere", sampleSphere);
  68121. effect.setFloat("samplesFactor", samplesFactor);
  68122. effect.setFloat("randTextureTiles", 4.0);
  68123. }
  68124. effect.setFloat("totalStrength", _this.totalStrength);
  68125. effect.setFloat("radius", _this.radius);
  68126. effect.setFloat("area", _this.area);
  68127. effect.setFloat("fallOff", _this.fallOff);
  68128. effect.setFloat("base", _this.base);
  68129. effect.setTexture("textureSampler", _this._depthTexture);
  68130. effect.setTexture("randomSampler", _this._randomTexture);
  68131. };
  68132. };
  68133. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  68134. var _this = this;
  68135. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  68136. this._ssaoCombinePostProcess.onApply = function (effect) {
  68137. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  68138. };
  68139. };
  68140. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  68141. var size = 512;
  68142. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  68143. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  68144. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  68145. var context = this._randomTexture.getContext();
  68146. var rand = function (min, max) {
  68147. return Math.random() * (max - min) + min;
  68148. };
  68149. var randVector = BABYLON.Vector3.Zero();
  68150. for (var x = 0; x < size; x++) {
  68151. for (var y = 0; y < size; y++) {
  68152. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  68153. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  68154. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  68155. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  68156. context.fillRect(x, y, 1, 1);
  68157. }
  68158. }
  68159. this._randomTexture.update(false);
  68160. };
  68161. __decorate([
  68162. BABYLON.serialize()
  68163. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  68164. __decorate([
  68165. BABYLON.serialize()
  68166. ], SSAORenderingPipeline.prototype, "radius", void 0);
  68167. __decorate([
  68168. BABYLON.serialize()
  68169. ], SSAORenderingPipeline.prototype, "area", void 0);
  68170. __decorate([
  68171. BABYLON.serialize()
  68172. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  68173. __decorate([
  68174. BABYLON.serialize()
  68175. ], SSAORenderingPipeline.prototype, "base", void 0);
  68176. return SSAORenderingPipeline;
  68177. }(BABYLON.PostProcessRenderPipeline));
  68178. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  68179. })(BABYLON || (BABYLON = {}));
  68180. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  68181. "use strict";
  68182. var BABYLON;
  68183. (function (BABYLON) {
  68184. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  68185. __extends(SSAO2RenderingPipeline, _super);
  68186. /**
  68187. * @constructor
  68188. * @param {string} name - The rendering pipeline name
  68189. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68190. * @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 }
  68191. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68192. */
  68193. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  68194. var _this = _super.call(this, scene.getEngine(), name) || this;
  68195. // Members
  68196. /**
  68197. * The PassPostProcess id in the pipeline that contains the original scene color
  68198. * @type {string}
  68199. */
  68200. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  68201. /**
  68202. * The SSAO PostProcess id in the pipeline
  68203. * @type {string}
  68204. */
  68205. _this.SSAORenderEffect = "SSAORenderEffect";
  68206. /**
  68207. * The horizontal blur PostProcess id in the pipeline
  68208. * @type {string}
  68209. */
  68210. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  68211. /**
  68212. * The vertical blur PostProcess id in the pipeline
  68213. * @type {string}
  68214. */
  68215. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  68216. /**
  68217. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  68218. * @type {string}
  68219. */
  68220. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  68221. /**
  68222. * The output strength of the SSAO post-process. Default value is 1.0.
  68223. * @type {number}
  68224. */
  68225. _this.totalStrength = 1.0;
  68226. /**
  68227. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  68228. * @type {number}
  68229. */
  68230. _this.maxZ = 100.0;
  68231. /**
  68232. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  68233. * @type {number}
  68234. */
  68235. _this.minZAspect = 0.2;
  68236. /**
  68237. * Number of samples used for the SSAO calculations. Default value is 8
  68238. * @type {number}
  68239. */
  68240. _this._samples = 8;
  68241. /**
  68242. * Are we using bilateral blur ?
  68243. * @type {boolean}
  68244. */
  68245. _this._expensiveBlur = true;
  68246. /**
  68247. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  68248. * @type {number}
  68249. */
  68250. _this.radius = 2.0;
  68251. /**
  68252. * The base color of the SSAO post-process
  68253. * The final result is "base + ssao" between [0, 1]
  68254. * @type {number}
  68255. */
  68256. _this.base = 0.1;
  68257. _this._firstUpdate = true;
  68258. _this._scene = scene;
  68259. if (!_this.isSupported) {
  68260. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  68261. return _this;
  68262. }
  68263. var ssaoRatio = ratio.ssaoRatio || ratio;
  68264. var blurRatio = ratio.blurRatio || ratio;
  68265. // Set up assets
  68266. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  68267. _this._createRandomTexture();
  68268. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  68269. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  68270. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  68271. _this._createSSAOPostProcess(1.0);
  68272. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  68273. _this._createSSAOCombinePostProcess(blurRatio);
  68274. // Set up pipeline
  68275. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  68276. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  68277. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  68278. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  68279. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  68280. // Finish
  68281. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68282. if (cameras)
  68283. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  68284. return _this;
  68285. }
  68286. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  68287. get: function () {
  68288. return this._samples;
  68289. },
  68290. set: function (n) {
  68291. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  68292. this._samples = n;
  68293. this._sampleSphere = this._generateHemisphere();
  68294. this._firstUpdate = true;
  68295. },
  68296. enumerable: true,
  68297. configurable: true
  68298. });
  68299. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  68300. get: function () {
  68301. return this._expensiveBlur;
  68302. },
  68303. set: function (b) {
  68304. 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"]);
  68305. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  68306. this._expensiveBlur = b;
  68307. this._firstUpdate = true;
  68308. },
  68309. enumerable: true,
  68310. configurable: true
  68311. });
  68312. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  68313. /**
  68314. * Support test.
  68315. * @type {boolean}
  68316. */
  68317. get: function () {
  68318. var engine = BABYLON.Engine.LastCreatedEngine;
  68319. if (!engine) {
  68320. return false;
  68321. }
  68322. return engine.getCaps().drawBuffersExtension;
  68323. },
  68324. enumerable: true,
  68325. configurable: true
  68326. });
  68327. // Public Methods
  68328. /**
  68329. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  68330. */
  68331. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  68332. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  68333. for (var i = 0; i < this._scene.cameras.length; i++) {
  68334. var camera = this._scene.cameras[i];
  68335. this._originalColorPostProcess.dispose(camera);
  68336. this._ssaoPostProcess.dispose(camera);
  68337. this._blurHPostProcess.dispose(camera);
  68338. this._blurVPostProcess.dispose(camera);
  68339. this._ssaoCombinePostProcess.dispose(camera);
  68340. }
  68341. this._randomTexture.dispose();
  68342. if (disableGeometryBufferRenderer)
  68343. this._scene.disableGeometryBufferRenderer();
  68344. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  68345. _super.prototype.dispose.call(this);
  68346. };
  68347. // Private Methods
  68348. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  68349. var _this = this;
  68350. this._samplerOffsets = [];
  68351. var expensive = this.expensiveBlur;
  68352. for (var i = -8; i < 8; i++) {
  68353. this._samplerOffsets.push(i * 2 + 0.5);
  68354. }
  68355. 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");
  68356. this._blurHPostProcess.onApply = function (effect) {
  68357. if (!_this._scene.activeCamera) {
  68358. return;
  68359. }
  68360. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  68361. effect.setFloat("near", _this._scene.activeCamera.minZ);
  68362. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  68363. effect.setFloat("radius", _this.radius);
  68364. effect.setTexture("depthSampler", _this._depthTexture);
  68365. if (_this._firstUpdate) {
  68366. effect.setArray("samplerOffsets", _this._samplerOffsets);
  68367. }
  68368. };
  68369. 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");
  68370. this._blurVPostProcess.onApply = function (effect) {
  68371. if (!_this._scene.activeCamera) {
  68372. return;
  68373. }
  68374. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  68375. effect.setFloat("near", _this._scene.activeCamera.minZ);
  68376. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  68377. effect.setFloat("radius", _this.radius);
  68378. effect.setTexture("depthSampler", _this._depthTexture);
  68379. if (_this._firstUpdate) {
  68380. effect.setArray("samplerOffsets", _this._samplerOffsets);
  68381. _this._firstUpdate = false;
  68382. }
  68383. };
  68384. };
  68385. SSAO2RenderingPipeline.prototype._rebuild = function () {
  68386. this._firstUpdate = true;
  68387. _super.prototype._rebuild.call(this);
  68388. };
  68389. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  68390. var numSamples = this.samples;
  68391. var result = [];
  68392. var vector, scale;
  68393. var rand = function (min, max) {
  68394. return Math.random() * (max - min) + min;
  68395. };
  68396. var i = 0;
  68397. while (i < numSamples) {
  68398. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  68399. vector.normalize();
  68400. scale = i / numSamples;
  68401. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  68402. vector.scaleInPlace(scale);
  68403. result.push(vector.x, vector.y, vector.z);
  68404. i++;
  68405. }
  68406. return result;
  68407. };
  68408. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  68409. var _this = this;
  68410. var numSamples = this.samples;
  68411. this._sampleSphere = this._generateHemisphere();
  68412. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  68413. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  68414. "base", "range", "projection", "near", "far", "texelSize",
  68415. "xViewport", "yViewport", "maxZ", "minZAspect"
  68416. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  68417. this._ssaoPostProcess.onApply = function (effect) {
  68418. if (_this._firstUpdate) {
  68419. effect.setArray3("sampleSphere", _this._sampleSphere);
  68420. effect.setFloat("randTextureTiles", 4.0);
  68421. }
  68422. if (!_this._scene.activeCamera) {
  68423. return;
  68424. }
  68425. effect.setFloat("samplesFactor", 1 / _this.samples);
  68426. effect.setFloat("totalStrength", _this.totalStrength);
  68427. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  68428. effect.setFloat("radius", _this.radius);
  68429. effect.setFloat("maxZ", _this.maxZ);
  68430. effect.setFloat("minZAspect", _this.minZAspect);
  68431. effect.setFloat("base", _this.base);
  68432. effect.setFloat("near", _this._scene.activeCamera.minZ);
  68433. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  68434. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  68435. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  68436. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  68437. effect.setTexture("textureSampler", _this._depthTexture);
  68438. effect.setTexture("normalSampler", _this._normalTexture);
  68439. effect.setTexture("randomSampler", _this._randomTexture);
  68440. };
  68441. };
  68442. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  68443. var _this = this;
  68444. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  68445. this._ssaoCombinePostProcess.onApply = function (effect) {
  68446. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  68447. };
  68448. };
  68449. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  68450. var size = 512;
  68451. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  68452. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  68453. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  68454. var context = this._randomTexture.getContext();
  68455. var rand = function (min, max) {
  68456. return Math.random() * (max - min) + min;
  68457. };
  68458. var randVector = BABYLON.Vector3.Zero();
  68459. for (var x = 0; x < size; x++) {
  68460. for (var y = 0; y < size; y++) {
  68461. randVector.x = rand(0.0, 1.0);
  68462. randVector.y = rand(0.0, 1.0);
  68463. randVector.z = 0.0;
  68464. randVector.normalize();
  68465. randVector.scaleInPlace(255);
  68466. randVector.x = Math.floor(randVector.x);
  68467. randVector.y = Math.floor(randVector.y);
  68468. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  68469. context.fillRect(x, y, 1, 1);
  68470. }
  68471. }
  68472. this._randomTexture.update(false);
  68473. };
  68474. __decorate([
  68475. BABYLON.serialize()
  68476. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  68477. __decorate([
  68478. BABYLON.serialize()
  68479. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  68480. __decorate([
  68481. BABYLON.serialize()
  68482. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  68483. __decorate([
  68484. BABYLON.serialize("samples")
  68485. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  68486. __decorate([
  68487. BABYLON.serialize("expensiveBlur")
  68488. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  68489. __decorate([
  68490. BABYLON.serialize()
  68491. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  68492. __decorate([
  68493. BABYLON.serialize()
  68494. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  68495. return SSAO2RenderingPipeline;
  68496. }(BABYLON.PostProcessRenderPipeline));
  68497. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  68498. })(BABYLON || (BABYLON = {}));
  68499. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  68500. "use strict";
  68501. // BABYLON.JS Chromatic Aberration GLSL Shader
  68502. // Author: Olivier Guyot
  68503. // Separates very slightly R, G and B colors on the edges of the screen
  68504. // Inspired by Francois Tarlier & Martins Upitis
  68505. var BABYLON;
  68506. (function (BABYLON) {
  68507. var LensRenderingPipeline = /** @class */ (function (_super) {
  68508. __extends(LensRenderingPipeline, _super);
  68509. /**
  68510. * @constructor
  68511. *
  68512. * Effect parameters are as follow:
  68513. * {
  68514. * chromatic_aberration: number; // from 0 to x (1 for realism)
  68515. * edge_blur: number; // from 0 to x (1 for realism)
  68516. * distortion: number; // from 0 to x (1 for realism)
  68517. * grain_amount: number; // from 0 to 1
  68518. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  68519. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  68520. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  68521. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  68522. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  68523. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  68524. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  68525. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  68526. * }
  68527. * Note: if an effect parameter is unset, effect is disabled
  68528. *
  68529. * @param {string} name - The rendering pipeline name
  68530. * @param {object} parameters - An object containing all parameters (see above)
  68531. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68532. * @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)
  68533. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68534. */
  68535. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  68536. if (ratio === void 0) { ratio = 1.0; }
  68537. var _this = _super.call(this, scene.getEngine(), name) || this;
  68538. // Lens effects can be of the following:
  68539. // - chromatic aberration (slight shift of RGB colors)
  68540. // - blur on the edge of the lens
  68541. // - lens distortion
  68542. // - depth-of-field blur & highlights enhancing
  68543. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  68544. // - grain effect (noise or custom texture)
  68545. // Two additional texture samplers are needed:
  68546. // - depth map (for depth-of-field)
  68547. // - grain texture
  68548. /**
  68549. * The chromatic aberration PostProcess id in the pipeline
  68550. * @type {string}
  68551. */
  68552. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  68553. /**
  68554. * The highlights enhancing PostProcess id in the pipeline
  68555. * @type {string}
  68556. */
  68557. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  68558. /**
  68559. * The depth-of-field PostProcess id in the pipeline
  68560. * @type {string}
  68561. */
  68562. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  68563. _this._scene = scene;
  68564. // Fetch texture samplers
  68565. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  68566. if (parameters.grain_texture) {
  68567. _this._grainTexture = parameters.grain_texture;
  68568. }
  68569. else {
  68570. _this._createGrainTexture();
  68571. }
  68572. // save parameters
  68573. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  68574. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  68575. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  68576. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  68577. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  68578. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  68579. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  68580. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  68581. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  68582. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  68583. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  68584. // Create effects
  68585. _this._createChromaticAberrationPostProcess(ratio);
  68586. _this._createHighlightsPostProcess(ratio);
  68587. _this._createDepthOfFieldPostProcess(ratio / 4);
  68588. // Set up pipeline
  68589. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  68590. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  68591. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  68592. if (_this._highlightsGain === -1) {
  68593. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  68594. }
  68595. // Finish
  68596. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68597. if (cameras) {
  68598. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  68599. }
  68600. return _this;
  68601. }
  68602. // public methods (self explanatory)
  68603. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  68604. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  68605. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  68606. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  68607. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  68608. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  68609. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  68610. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  68611. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  68612. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  68613. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  68614. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  68615. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  68616. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  68617. };
  68618. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  68619. this._highlightsPostProcess.updateEffect();
  68620. };
  68621. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  68622. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  68623. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  68624. this._highlightsGain = amount;
  68625. };
  68626. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  68627. if (this._highlightsGain === -1) {
  68628. this._highlightsGain = 1.0;
  68629. }
  68630. this._highlightsThreshold = amount;
  68631. };
  68632. LensRenderingPipeline.prototype.disableHighlights = function () {
  68633. this._highlightsGain = -1;
  68634. };
  68635. /**
  68636. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  68637. */
  68638. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  68639. if (disableDepthRender === void 0) { disableDepthRender = false; }
  68640. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  68641. this._chromaticAberrationPostProcess = null;
  68642. this._highlightsPostProcess = null;
  68643. this._depthOfFieldPostProcess = null;
  68644. this._grainTexture.dispose();
  68645. if (disableDepthRender)
  68646. this._scene.disableDepthRenderer();
  68647. };
  68648. // colors shifting and distortion
  68649. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  68650. var _this = this;
  68651. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  68652. [], // samplers
  68653. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  68654. this._chromaticAberrationPostProcess.onApply = function (effect) {
  68655. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  68656. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  68657. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  68658. effect.setFloat('radialIntensity', 1);
  68659. effect.setFloat2('direction', 17, 17);
  68660. effect.setFloat2('centerPosition', 0.5, 0.5);
  68661. };
  68662. };
  68663. // highlights enhancing
  68664. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  68665. var _this = this;
  68666. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  68667. [], // samplers
  68668. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  68669. this._highlightsPostProcess.onApply = function (effect) {
  68670. effect.setFloat('gain', _this._highlightsGain);
  68671. effect.setFloat('threshold', _this._highlightsThreshold);
  68672. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  68673. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  68674. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  68675. };
  68676. };
  68677. // colors shifting and distortion
  68678. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  68679. var _this = this;
  68680. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  68681. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  68682. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  68683. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  68684. this._depthOfFieldPostProcess.onApply = function (effect) {
  68685. effect.setTexture("depthSampler", _this._depthTexture);
  68686. effect.setTexture("grainSampler", _this._grainTexture);
  68687. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  68688. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  68689. effect.setFloat('grain_amount', _this._grainAmount);
  68690. effect.setBool('blur_noise', _this._blurNoise);
  68691. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  68692. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  68693. effect.setFloat('distortion', _this._distortion);
  68694. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  68695. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  68696. effect.setFloat('aperture', _this._dofAperture);
  68697. effect.setFloat('darken', _this._dofDarken);
  68698. effect.setFloat('edge_blur', _this._edgeBlur);
  68699. effect.setBool('highlights', (_this._highlightsGain !== -1));
  68700. if (_this._scene.activeCamera) {
  68701. effect.setFloat('near', _this._scene.activeCamera.minZ);
  68702. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  68703. }
  68704. };
  68705. };
  68706. // creates a black and white random noise texture, 512x512
  68707. LensRenderingPipeline.prototype._createGrainTexture = function () {
  68708. var size = 512;
  68709. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  68710. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  68711. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  68712. var context = this._grainTexture.getContext();
  68713. var rand = function (min, max) {
  68714. return Math.random() * (max - min) + min;
  68715. };
  68716. var value;
  68717. for (var x = 0; x < size; x++) {
  68718. for (var y = 0; y < size; y++) {
  68719. value = Math.floor(rand(0.42, 0.58) * 255);
  68720. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  68721. context.fillRect(x, y, 1, 1);
  68722. }
  68723. }
  68724. this._grainTexture.update(false);
  68725. };
  68726. return LensRenderingPipeline;
  68727. }(BABYLON.PostProcessRenderPipeline));
  68728. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  68729. })(BABYLON || (BABYLON = {}));
  68730. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  68731. "use strict";
  68732. var BABYLON;
  68733. (function (BABYLON) {
  68734. var StandardRenderingPipeline = /** @class */ (function (_super) {
  68735. __extends(StandardRenderingPipeline, _super);
  68736. /**
  68737. * @constructor
  68738. * @param {string} name - The rendering pipeline name
  68739. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  68740. * @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)
  68741. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  68742. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  68743. */
  68744. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  68745. if (originalPostProcess === void 0) { originalPostProcess = null; }
  68746. var _this = _super.call(this, scene.getEngine(), name) || this;
  68747. _this.downSampleX4PostProcess = null;
  68748. _this.brightPassPostProcess = null;
  68749. _this.blurHPostProcesses = [];
  68750. _this.blurVPostProcesses = [];
  68751. _this.textureAdderPostProcess = null;
  68752. _this.volumetricLightPostProcess = null;
  68753. _this.volumetricLightSmoothXPostProcess = null;
  68754. _this.volumetricLightSmoothYPostProcess = null;
  68755. _this.volumetricLightMergePostProces = null;
  68756. _this.volumetricLightFinalPostProcess = null;
  68757. _this.luminancePostProcess = null;
  68758. _this.luminanceDownSamplePostProcesses = [];
  68759. _this.hdrPostProcess = null;
  68760. _this.textureAdderFinalPostProcess = null;
  68761. _this.lensFlareFinalPostProcess = null;
  68762. _this.hdrFinalPostProcess = null;
  68763. _this.lensFlarePostProcess = null;
  68764. _this.lensFlareComposePostProcess = null;
  68765. _this.motionBlurPostProcess = null;
  68766. _this.depthOfFieldPostProcess = null;
  68767. // Values
  68768. _this.brightThreshold = 1.0;
  68769. _this.blurWidth = 512.0;
  68770. _this.horizontalBlur = false;
  68771. _this.exposure = 1.0;
  68772. _this.lensTexture = null;
  68773. _this.volumetricLightCoefficient = 0.2;
  68774. _this.volumetricLightPower = 4.0;
  68775. _this.volumetricLightBlurScale = 64.0;
  68776. _this.sourceLight = null;
  68777. _this.hdrMinimumLuminance = 1.0;
  68778. _this.hdrDecreaseRate = 0.5;
  68779. _this.hdrIncreaseRate = 0.5;
  68780. _this.lensColorTexture = null;
  68781. _this.lensFlareStrength = 20.0;
  68782. _this.lensFlareGhostDispersal = 1.4;
  68783. _this.lensFlareHaloWidth = 0.7;
  68784. _this.lensFlareDistortionStrength = 16.0;
  68785. _this.lensStarTexture = null;
  68786. _this.lensFlareDirtTexture = null;
  68787. _this.depthOfFieldDistance = 10.0;
  68788. _this.depthOfFieldBlurWidth = 64.0;
  68789. _this.motionStrength = 1.0;
  68790. // IAnimatable
  68791. _this.animations = [];
  68792. _this._currentDepthOfFieldSource = null;
  68793. _this._hdrCurrentLuminance = 1.0;
  68794. // Getters and setters
  68795. _this._bloomEnabled = true;
  68796. _this._depthOfFieldEnabled = false;
  68797. _this._vlsEnabled = false;
  68798. _this._lensFlareEnabled = false;
  68799. _this._hdrEnabled = false;
  68800. _this._motionBlurEnabled = false;
  68801. _this._motionBlurSamples = 64.0;
  68802. _this._volumetricLightStepsCount = 50.0;
  68803. _this._cameras = cameras || [];
  68804. // Initialize
  68805. _this._scene = scene;
  68806. _this._basePostProcess = originalPostProcess;
  68807. _this._ratio = ratio;
  68808. // Misc
  68809. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  68810. // Finish
  68811. scene.postProcessRenderPipelineManager.addPipeline(_this);
  68812. _this._buildPipeline();
  68813. return _this;
  68814. }
  68815. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  68816. get: function () {
  68817. return this._bloomEnabled;
  68818. },
  68819. set: function (enabled) {
  68820. if (this._bloomEnabled === enabled) {
  68821. return;
  68822. }
  68823. this._bloomEnabled = enabled;
  68824. this._buildPipeline();
  68825. },
  68826. enumerable: true,
  68827. configurable: true
  68828. });
  68829. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  68830. get: function () {
  68831. return this._depthOfFieldEnabled;
  68832. },
  68833. set: function (enabled) {
  68834. if (this._depthOfFieldEnabled === enabled) {
  68835. return;
  68836. }
  68837. this._depthOfFieldEnabled = enabled;
  68838. this._buildPipeline();
  68839. },
  68840. enumerable: true,
  68841. configurable: true
  68842. });
  68843. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  68844. get: function () {
  68845. return this._lensFlareEnabled;
  68846. },
  68847. set: function (enabled) {
  68848. if (this._lensFlareEnabled === enabled) {
  68849. return;
  68850. }
  68851. this._lensFlareEnabled = enabled;
  68852. this._buildPipeline();
  68853. },
  68854. enumerable: true,
  68855. configurable: true
  68856. });
  68857. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  68858. get: function () {
  68859. return this._hdrEnabled;
  68860. },
  68861. set: function (enabled) {
  68862. if (this._hdrEnabled === enabled) {
  68863. return;
  68864. }
  68865. this._hdrEnabled = enabled;
  68866. this._buildPipeline();
  68867. },
  68868. enumerable: true,
  68869. configurable: true
  68870. });
  68871. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  68872. get: function () {
  68873. return this._vlsEnabled;
  68874. },
  68875. set: function (enabled) {
  68876. if (this._vlsEnabled === enabled) {
  68877. return;
  68878. }
  68879. if (enabled) {
  68880. var geometry = this._scene.enableGeometryBufferRenderer();
  68881. if (!geometry) {
  68882. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  68883. return;
  68884. }
  68885. }
  68886. this._vlsEnabled = enabled;
  68887. this._buildPipeline();
  68888. },
  68889. enumerable: true,
  68890. configurable: true
  68891. });
  68892. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  68893. get: function () {
  68894. return this._motionBlurEnabled;
  68895. },
  68896. set: function (enabled) {
  68897. if (this._motionBlurEnabled === enabled) {
  68898. return;
  68899. }
  68900. this._motionBlurEnabled = enabled;
  68901. this._buildPipeline();
  68902. },
  68903. enumerable: true,
  68904. configurable: true
  68905. });
  68906. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  68907. get: function () {
  68908. return this._volumetricLightStepsCount;
  68909. },
  68910. set: function (count) {
  68911. if (this.volumetricLightPostProcess) {
  68912. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  68913. }
  68914. this._volumetricLightStepsCount = count;
  68915. },
  68916. enumerable: true,
  68917. configurable: true
  68918. });
  68919. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  68920. get: function () {
  68921. return this._motionBlurSamples;
  68922. },
  68923. set: function (samples) {
  68924. if (this.motionBlurPostProcess) {
  68925. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  68926. }
  68927. this._motionBlurSamples = samples;
  68928. },
  68929. enumerable: true,
  68930. configurable: true
  68931. });
  68932. StandardRenderingPipeline.prototype._buildPipeline = function () {
  68933. var _this = this;
  68934. var ratio = this._ratio;
  68935. var scene = this._scene;
  68936. this._disposePostProcesses();
  68937. this._reset();
  68938. // Create pass post-process
  68939. if (!this._basePostProcess) {
  68940. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  68941. this.originalPostProcess.onApply = function (effect) {
  68942. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  68943. };
  68944. }
  68945. else {
  68946. this.originalPostProcess = this._basePostProcess;
  68947. }
  68948. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  68949. this._currentDepthOfFieldSource = this.originalPostProcess;
  68950. if (this._vlsEnabled) {
  68951. // Create volumetric light
  68952. this._createVolumetricLightPostProcess(scene, ratio);
  68953. // Create volumetric light final post-process
  68954. 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);
  68955. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  68956. }
  68957. if (this._bloomEnabled) {
  68958. // Create down sample X4 post-process
  68959. this._createDownSampleX4PostProcess(scene, ratio / 2);
  68960. // Create bright pass post-process
  68961. this._createBrightPassPostProcess(scene, ratio / 2);
  68962. // Create gaussian blur post-processes (down sampling blurs)
  68963. this._createBlurPostProcesses(scene, ratio / 4, 1);
  68964. // Create texture adder post-process
  68965. this._createTextureAdderPostProcess(scene, ratio);
  68966. // Create depth-of-field source post-process
  68967. 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);
  68968. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  68969. }
  68970. if (this._lensFlareEnabled) {
  68971. // Create lens flare post-process
  68972. this._createLensFlarePostProcess(scene, ratio);
  68973. // Create depth-of-field source post-process post lens-flare and disable it now
  68974. 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);
  68975. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  68976. }
  68977. if (this._hdrEnabled) {
  68978. // Create luminance
  68979. this._createLuminancePostProcesses(scene, this._floatTextureType);
  68980. // Create HDR
  68981. this._createHdrPostProcess(scene, ratio);
  68982. // Create depth-of-field source post-process post hdr and disable it now
  68983. 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);
  68984. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  68985. }
  68986. if (this._depthOfFieldEnabled) {
  68987. // Create gaussian blur used by depth-of-field
  68988. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  68989. // Create depth-of-field post-process
  68990. this._createDepthOfFieldPostProcess(scene, ratio);
  68991. }
  68992. if (this._motionBlurEnabled) {
  68993. // Create motion blur post-process
  68994. this._createMotionBlurPostProcess(scene, ratio);
  68995. }
  68996. if (this._cameras !== null) {
  68997. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  68998. }
  68999. };
  69000. // Down Sample X4 Post-Processs
  69001. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  69002. var _this = this;
  69003. var downSampleX4Offsets = new Array(32);
  69004. 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);
  69005. this.downSampleX4PostProcess.onApply = function (effect) {
  69006. var id = 0;
  69007. var width = _this.downSampleX4PostProcess.width;
  69008. var height = _this.downSampleX4PostProcess.height;
  69009. for (var i = -2; i < 2; i++) {
  69010. for (var j = -2; j < 2; j++) {
  69011. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  69012. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  69013. id += 2;
  69014. }
  69015. }
  69016. effect.setArray2("dsOffsets", downSampleX4Offsets);
  69017. };
  69018. // Add to pipeline
  69019. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  69020. };
  69021. // Brightpass Post-Process
  69022. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  69023. var _this = this;
  69024. var brightOffsets = new Array(8);
  69025. 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);
  69026. this.brightPassPostProcess.onApply = function (effect) {
  69027. var sU = (1.0 / _this.brightPassPostProcess.width);
  69028. var sV = (1.0 / _this.brightPassPostProcess.height);
  69029. brightOffsets[0] = -0.5 * sU;
  69030. brightOffsets[1] = 0.5 * sV;
  69031. brightOffsets[2] = 0.5 * sU;
  69032. brightOffsets[3] = 0.5 * sV;
  69033. brightOffsets[4] = -0.5 * sU;
  69034. brightOffsets[5] = -0.5 * sV;
  69035. brightOffsets[6] = 0.5 * sU;
  69036. brightOffsets[7] = -0.5 * sV;
  69037. effect.setArray2("dsOffsets", brightOffsets);
  69038. effect.setFloat("brightThreshold", _this.brightThreshold);
  69039. };
  69040. // Add to pipeline
  69041. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  69042. };
  69043. // Create blur H&V post-processes
  69044. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  69045. var _this = this;
  69046. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  69047. var engine = scene.getEngine();
  69048. 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);
  69049. 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);
  69050. blurX.onActivateObservable.add(function () {
  69051. var dw = blurX.width / engine.getRenderWidth();
  69052. blurX.kernel = _this[blurWidthKey] * dw;
  69053. });
  69054. blurY.onActivateObservable.add(function () {
  69055. var dw = blurY.height / engine.getRenderHeight();
  69056. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  69057. });
  69058. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  69059. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  69060. this.blurHPostProcesses.push(blurX);
  69061. this.blurVPostProcesses.push(blurY);
  69062. };
  69063. // Create texture adder post-process
  69064. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  69065. var _this = this;
  69066. 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);
  69067. this.textureAdderPostProcess.onApply = function (effect) {
  69068. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  69069. effect.setTexture("lensSampler", _this.lensTexture);
  69070. effect.setFloat("exposure", _this.exposure);
  69071. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  69072. };
  69073. // Add to pipeline
  69074. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  69075. };
  69076. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  69077. var _this = this;
  69078. var geometryRenderer = scene.enableGeometryBufferRenderer();
  69079. geometryRenderer.enablePosition = true;
  69080. var geometry = geometryRenderer.getGBuffer();
  69081. // Base post-process
  69082. 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));
  69083. var depthValues = BABYLON.Vector2.Zero();
  69084. this.volumetricLightPostProcess.onApply = function (effect) {
  69085. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  69086. var generator = _this.sourceLight.getShadowGenerator();
  69087. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  69088. effect.setTexture("positionSampler", geometry.textures[2]);
  69089. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  69090. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  69091. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  69092. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  69093. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  69094. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  69095. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  69096. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  69097. effect.setVector2("depthValues", depthValues);
  69098. }
  69099. };
  69100. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  69101. // Smooth
  69102. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  69103. // Merge
  69104. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  69105. this.volumetricLightMergePostProces.onApply = function (effect) {
  69106. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  69107. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  69108. };
  69109. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  69110. };
  69111. // Create luminance
  69112. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  69113. var _this = this;
  69114. // Create luminance
  69115. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  69116. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  69117. var offsets = [];
  69118. this.luminancePostProcess.onApply = function (effect) {
  69119. var sU = (1.0 / _this.luminancePostProcess.width);
  69120. var sV = (1.0 / _this.luminancePostProcess.height);
  69121. offsets[0] = -0.5 * sU;
  69122. offsets[1] = 0.5 * sV;
  69123. offsets[2] = 0.5 * sU;
  69124. offsets[3] = 0.5 * sV;
  69125. offsets[4] = -0.5 * sU;
  69126. offsets[5] = -0.5 * sV;
  69127. offsets[6] = 0.5 * sU;
  69128. offsets[7] = -0.5 * sV;
  69129. effect.setArray2("lumOffsets", offsets);
  69130. };
  69131. // Add to pipeline
  69132. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  69133. // Create down sample luminance
  69134. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  69135. var size = Math.pow(3, i);
  69136. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  69137. if (i === 0) {
  69138. defines += "#define FINAL_DOWN_SAMPLER";
  69139. }
  69140. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  69141. this.luminanceDownSamplePostProcesses.push(postProcess);
  69142. }
  69143. // Create callbacks and add effects
  69144. var lastLuminance = this.luminancePostProcess;
  69145. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  69146. var downSampleOffsets = new Array(18);
  69147. pp.onApply = function (effect) {
  69148. if (!lastLuminance) {
  69149. return;
  69150. }
  69151. var id = 0;
  69152. for (var x = -1; x < 2; x++) {
  69153. for (var y = -1; y < 2; y++) {
  69154. downSampleOffsets[id] = x / lastLuminance.width;
  69155. downSampleOffsets[id + 1] = y / lastLuminance.height;
  69156. id += 2;
  69157. }
  69158. }
  69159. effect.setArray2("dsOffsets", downSampleOffsets);
  69160. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  69161. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  69162. lastLuminance = _this.luminancePostProcess;
  69163. }
  69164. else {
  69165. lastLuminance = pp;
  69166. }
  69167. };
  69168. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  69169. pp.onAfterRender = function (effect) {
  69170. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  69171. 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);
  69172. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  69173. };
  69174. }
  69175. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  69176. });
  69177. };
  69178. // Create HDR post-process
  69179. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  69180. var _this = this;
  69181. 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);
  69182. var outputLiminance = 1;
  69183. var time = 0;
  69184. var lastTime = 0;
  69185. this.hdrPostProcess.onApply = function (effect) {
  69186. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  69187. time += scene.getEngine().getDeltaTime();
  69188. if (outputLiminance < 0) {
  69189. outputLiminance = _this._hdrCurrentLuminance;
  69190. }
  69191. else {
  69192. var dt = (lastTime - time) / 1000.0;
  69193. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  69194. outputLiminance += _this.hdrDecreaseRate * dt;
  69195. }
  69196. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  69197. outputLiminance -= _this.hdrIncreaseRate * dt;
  69198. }
  69199. else {
  69200. outputLiminance = _this._hdrCurrentLuminance;
  69201. }
  69202. }
  69203. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  69204. effect.setFloat("averageLuminance", outputLiminance);
  69205. lastTime = time;
  69206. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  69207. };
  69208. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  69209. };
  69210. // Create lens flare post-process
  69211. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  69212. var _this = this;
  69213. 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);
  69214. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  69215. this._createBlurPostProcesses(scene, ratio / 4, 2);
  69216. 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);
  69217. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  69218. var resolution = new BABYLON.Vector2(0, 0);
  69219. // Lens flare
  69220. this.lensFlarePostProcess.onApply = function (effect) {
  69221. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  69222. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  69223. effect.setFloat("strength", _this.lensFlareStrength);
  69224. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  69225. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  69226. // Shift
  69227. resolution.x = _this.lensFlarePostProcess.width;
  69228. resolution.y = _this.lensFlarePostProcess.height;
  69229. effect.setVector2("resolution", resolution);
  69230. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  69231. };
  69232. // Compose
  69233. 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);
  69234. 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);
  69235. this.lensFlareComposePostProcess.onApply = function (effect) {
  69236. if (!_this._scene.activeCamera) {
  69237. return;
  69238. }
  69239. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  69240. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  69241. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  69242. // Lens start rotation matrix
  69243. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  69244. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  69245. 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));
  69246. camRot *= 4.0;
  69247. 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);
  69248. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  69249. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  69250. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  69251. };
  69252. };
  69253. // Create depth-of-field post-process
  69254. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  69255. var _this = this;
  69256. 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);
  69257. this.depthOfFieldPostProcess.onApply = function (effect) {
  69258. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  69259. effect.setTexture("depthSampler", _this._getDepthTexture());
  69260. effect.setFloat("distance", _this.depthOfFieldDistance);
  69261. };
  69262. // Add to pipeline
  69263. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  69264. };
  69265. // Create motion blur post-process
  69266. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  69267. var _this = this;
  69268. 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);
  69269. var motionScale = 0;
  69270. var prevViewProjection = BABYLON.Matrix.Identity();
  69271. var invViewProjection = BABYLON.Matrix.Identity();
  69272. var viewProjection = BABYLON.Matrix.Identity();
  69273. var screenSize = BABYLON.Vector2.Zero();
  69274. this.motionBlurPostProcess.onApply = function (effect) {
  69275. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  69276. viewProjection.invertToRef(invViewProjection);
  69277. effect.setMatrix("inverseViewProjection", invViewProjection);
  69278. effect.setMatrix("prevViewProjection", prevViewProjection);
  69279. prevViewProjection = viewProjection;
  69280. screenSize.x = _this.motionBlurPostProcess.width;
  69281. screenSize.y = _this.motionBlurPostProcess.height;
  69282. effect.setVector2("screenSize", screenSize);
  69283. motionScale = scene.getEngine().getFps() / 60.0;
  69284. effect.setFloat("motionScale", motionScale);
  69285. effect.setFloat("motionStrength", _this.motionStrength);
  69286. effect.setTexture("depthSampler", _this._getDepthTexture());
  69287. };
  69288. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  69289. };
  69290. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  69291. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  69292. var renderer = this._scene.enableGeometryBufferRenderer();
  69293. return renderer.getGBuffer().textures[0];
  69294. }
  69295. return this._scene.enableDepthRenderer().getDepthMap();
  69296. };
  69297. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  69298. for (var i = 0; i < this._cameras.length; i++) {
  69299. var camera = this._cameras[i];
  69300. if (this.originalPostProcess) {
  69301. this.originalPostProcess.dispose(camera);
  69302. }
  69303. if (this.downSampleX4PostProcess) {
  69304. this.downSampleX4PostProcess.dispose(camera);
  69305. }
  69306. if (this.brightPassPostProcess) {
  69307. this.brightPassPostProcess.dispose(camera);
  69308. }
  69309. if (this.textureAdderPostProcess) {
  69310. this.textureAdderPostProcess.dispose(camera);
  69311. }
  69312. if (this.textureAdderFinalPostProcess) {
  69313. this.textureAdderFinalPostProcess.dispose(camera);
  69314. }
  69315. if (this.volumetricLightPostProcess) {
  69316. this.volumetricLightPostProcess.dispose(camera);
  69317. }
  69318. if (this.volumetricLightSmoothXPostProcess) {
  69319. this.volumetricLightSmoothXPostProcess.dispose(camera);
  69320. }
  69321. if (this.volumetricLightSmoothYPostProcess) {
  69322. this.volumetricLightSmoothYPostProcess.dispose(camera);
  69323. }
  69324. if (this.volumetricLightMergePostProces) {
  69325. this.volumetricLightMergePostProces.dispose(camera);
  69326. }
  69327. if (this.volumetricLightFinalPostProcess) {
  69328. this.volumetricLightFinalPostProcess.dispose(camera);
  69329. }
  69330. if (this.lensFlarePostProcess) {
  69331. this.lensFlarePostProcess.dispose(camera);
  69332. }
  69333. if (this.lensFlareComposePostProcess) {
  69334. this.lensFlareComposePostProcess.dispose(camera);
  69335. }
  69336. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  69337. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  69338. }
  69339. if (this.luminancePostProcess) {
  69340. this.luminancePostProcess.dispose(camera);
  69341. }
  69342. if (this.hdrPostProcess) {
  69343. this.hdrPostProcess.dispose(camera);
  69344. }
  69345. if (this.hdrFinalPostProcess) {
  69346. this.hdrFinalPostProcess.dispose(camera);
  69347. }
  69348. if (this.depthOfFieldPostProcess) {
  69349. this.depthOfFieldPostProcess.dispose(camera);
  69350. }
  69351. if (this.motionBlurPostProcess) {
  69352. this.motionBlurPostProcess.dispose(camera);
  69353. }
  69354. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  69355. this.blurHPostProcesses[j].dispose(camera);
  69356. }
  69357. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  69358. this.blurVPostProcesses[j].dispose(camera);
  69359. }
  69360. }
  69361. this.originalPostProcess = null;
  69362. this.downSampleX4PostProcess = null;
  69363. this.brightPassPostProcess = null;
  69364. this.textureAdderPostProcess = null;
  69365. this.textureAdderFinalPostProcess = null;
  69366. this.volumetricLightPostProcess = null;
  69367. this.volumetricLightSmoothXPostProcess = null;
  69368. this.volumetricLightSmoothYPostProcess = null;
  69369. this.volumetricLightMergePostProces = null;
  69370. this.volumetricLightFinalPostProcess = null;
  69371. this.lensFlarePostProcess = null;
  69372. this.lensFlareComposePostProcess = null;
  69373. this.luminancePostProcess = null;
  69374. this.hdrPostProcess = null;
  69375. this.hdrFinalPostProcess = null;
  69376. this.depthOfFieldPostProcess = null;
  69377. this.motionBlurPostProcess = null;
  69378. this.luminanceDownSamplePostProcesses = [];
  69379. this.blurHPostProcesses = [];
  69380. this.blurVPostProcesses = [];
  69381. };
  69382. // Dispose
  69383. StandardRenderingPipeline.prototype.dispose = function () {
  69384. this._disposePostProcesses();
  69385. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  69386. _super.prototype.dispose.call(this);
  69387. };
  69388. // Serialize rendering pipeline
  69389. StandardRenderingPipeline.prototype.serialize = function () {
  69390. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  69391. serializationObject.customType = "StandardRenderingPipeline";
  69392. return serializationObject;
  69393. };
  69394. /**
  69395. * Static members
  69396. */
  69397. // Parse serialized pipeline
  69398. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  69399. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  69400. };
  69401. // Luminance steps
  69402. StandardRenderingPipeline.LuminanceSteps = 6;
  69403. __decorate([
  69404. BABYLON.serialize()
  69405. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  69406. __decorate([
  69407. BABYLON.serialize()
  69408. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  69409. __decorate([
  69410. BABYLON.serialize()
  69411. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  69412. __decorate([
  69413. BABYLON.serialize()
  69414. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  69415. __decorate([
  69416. BABYLON.serializeAsTexture("lensTexture")
  69417. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  69418. __decorate([
  69419. BABYLON.serialize()
  69420. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  69421. __decorate([
  69422. BABYLON.serialize()
  69423. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  69424. __decorate([
  69425. BABYLON.serialize()
  69426. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  69427. __decorate([
  69428. BABYLON.serialize()
  69429. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  69430. __decorate([
  69431. BABYLON.serialize()
  69432. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  69433. __decorate([
  69434. BABYLON.serialize()
  69435. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  69436. __decorate([
  69437. BABYLON.serializeAsTexture("lensColorTexture")
  69438. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  69439. __decorate([
  69440. BABYLON.serialize()
  69441. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  69442. __decorate([
  69443. BABYLON.serialize()
  69444. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  69445. __decorate([
  69446. BABYLON.serialize()
  69447. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  69448. __decorate([
  69449. BABYLON.serialize()
  69450. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  69451. __decorate([
  69452. BABYLON.serializeAsTexture("lensStarTexture")
  69453. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  69454. __decorate([
  69455. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  69456. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  69457. __decorate([
  69458. BABYLON.serialize()
  69459. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  69460. __decorate([
  69461. BABYLON.serialize()
  69462. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  69463. __decorate([
  69464. BABYLON.serialize()
  69465. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  69466. __decorate([
  69467. BABYLON.serialize()
  69468. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  69469. __decorate([
  69470. BABYLON.serialize()
  69471. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  69472. __decorate([
  69473. BABYLON.serialize()
  69474. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  69475. __decorate([
  69476. BABYLON.serialize()
  69477. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  69478. __decorate([
  69479. BABYLON.serialize()
  69480. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  69481. __decorate([
  69482. BABYLON.serialize()
  69483. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  69484. __decorate([
  69485. BABYLON.serialize()
  69486. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  69487. __decorate([
  69488. BABYLON.serialize()
  69489. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  69490. __decorate([
  69491. BABYLON.serialize()
  69492. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  69493. return StandardRenderingPipeline;
  69494. }(BABYLON.PostProcessRenderPipeline));
  69495. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  69496. })(BABYLON || (BABYLON = {}));
  69497. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  69498. "use strict";
  69499. var BABYLON;
  69500. (function (BABYLON) {
  69501. var FxaaPostProcess = /** @class */ (function (_super) {
  69502. __extends(FxaaPostProcess, _super);
  69503. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  69504. if (camera === void 0) { camera = null; }
  69505. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69506. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  69507. _this.onApplyObservable.add(function (effect) {
  69508. var texelSize = _this.texelSize;
  69509. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  69510. });
  69511. return _this;
  69512. }
  69513. return FxaaPostProcess;
  69514. }(BABYLON.PostProcess));
  69515. BABYLON.FxaaPostProcess = FxaaPostProcess;
  69516. })(BABYLON || (BABYLON = {}));
  69517. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  69518. "use strict";
  69519. var BABYLON;
  69520. (function (BABYLON) {
  69521. /**
  69522. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  69523. */
  69524. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  69525. __extends(ChromaticAberrationPostProcess, _super);
  69526. /**
  69527. * Creates a new instance of @see ChromaticAberrationPostProcess
  69528. * @param name The name of the effect.
  69529. * @param screenWidth The width of the screen to apply the effect on.
  69530. * @param screenHeight The height of the screen to apply the effect on.
  69531. * @param options The required width/height ratio to downsize to before computing the render pass.
  69532. * @param camera The camera to apply the render pass to.
  69533. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69534. * @param engine The engine which the post process will be applied. (default: current engine)
  69535. * @param reusable If the post process can be reused on the same frame. (default: false)
  69536. * @param textureType Type of textures used when performing the post process. (default: 0)
  69537. * @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)
  69538. */
  69539. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69540. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69541. if (blockCompilation === void 0) { blockCompilation = false; }
  69542. 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;
  69543. /**
  69544. * The amount of seperation of rgb channels (default: 30)
  69545. */
  69546. _this.aberrationAmount = 30;
  69547. /**
  69548. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  69549. */
  69550. _this.radialIntensity = 0;
  69551. /**
  69552. * 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))
  69553. */
  69554. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  69555. /**
  69556. * 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))
  69557. */
  69558. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  69559. _this.onApplyObservable.add(function (effect) {
  69560. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  69561. effect.setFloat('screen_width', screenWidth);
  69562. effect.setFloat('screen_height', screenHeight);
  69563. effect.setFloat('radialIntensity', _this.radialIntensity);
  69564. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  69565. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  69566. });
  69567. return _this;
  69568. }
  69569. return ChromaticAberrationPostProcess;
  69570. }(BABYLON.PostProcess));
  69571. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  69572. })(BABYLON || (BABYLON = {}));
  69573. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  69574. "use strict";
  69575. var BABYLON;
  69576. (function (BABYLON) {
  69577. /**
  69578. * The SharpenPostProcess applies a sharpen kernel to every pixel
  69579. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  69580. */
  69581. var SharpenPostProcess = /** @class */ (function (_super) {
  69582. __extends(SharpenPostProcess, _super);
  69583. /**
  69584. * Creates a new instance of @see ConvolutionPostProcess
  69585. * @param name The name of the effect.
  69586. * @param options The required width/height ratio to downsize to before computing the render pass.
  69587. * @param camera The camera to apply the render pass to.
  69588. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69589. * @param engine The engine which the post process will be applied. (default: current engine)
  69590. * @param reusable If the post process can be reused on the same frame. (default: false)
  69591. * @param textureType Type of textures used when performing the post process. (default: 0)
  69592. * @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)
  69593. */
  69594. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69595. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69596. if (blockCompilation === void 0) { blockCompilation = false; }
  69597. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  69598. /**
  69599. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  69600. */
  69601. _this.colorAmount = 1.0;
  69602. /**
  69603. * How much sharpness should be applied (default: 0.3)
  69604. */
  69605. _this.edgeAmount = 0.3;
  69606. _this.onApply = function (effect) {
  69607. effect.setFloat2("screenSize", _this.width, _this.height);
  69608. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  69609. };
  69610. return _this;
  69611. }
  69612. return SharpenPostProcess;
  69613. }(BABYLON.PostProcess));
  69614. BABYLON.SharpenPostProcess = SharpenPostProcess;
  69615. })(BABYLON || (BABYLON = {}));
  69616. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  69617. "use strict";
  69618. var BABYLON;
  69619. (function (BABYLON) {
  69620. /**
  69621. * The Blur Post Process which blurs an image based on a kernel and direction.
  69622. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  69623. */
  69624. var BlurPostProcess = /** @class */ (function (_super) {
  69625. __extends(BlurPostProcess, _super);
  69626. /**
  69627. * Creates a new instance of @see BlurPostProcess
  69628. * @param name The name of the effect.
  69629. * @param direction The direction in which to blur the image.
  69630. * @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.
  69631. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  69632. * @param camera The camera to apply the render pass to.
  69633. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69634. * @param engine The engine which the post process will be applied. (default: current engine)
  69635. * @param reusable If the post process can be reused on the same frame. (default: false)
  69636. * @param textureType Type of textures used when performing the post process. (default: 0)
  69637. * @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)
  69638. */
  69639. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  69640. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69641. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69642. if (defines === void 0) { defines = ""; }
  69643. if (blockCompilation === void 0) { blockCompilation = false; }
  69644. 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;
  69645. _this.direction = direction;
  69646. _this.blockCompilation = blockCompilation;
  69647. _this._packedFloat = false;
  69648. _this._staticDefines = "";
  69649. _this._staticDefines = defines;
  69650. _this.onApplyObservable.add(function (effect) {
  69651. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  69652. });
  69653. _this.kernel = kernel;
  69654. return _this;
  69655. }
  69656. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  69657. /**
  69658. * Gets the length in pixels of the blur sample region
  69659. */
  69660. get: function () {
  69661. return this._idealKernel;
  69662. },
  69663. /**
  69664. * Sets the length in pixels of the blur sample region
  69665. */
  69666. set: function (v) {
  69667. if (this._idealKernel === v) {
  69668. return;
  69669. }
  69670. v = Math.max(v, 1);
  69671. this._idealKernel = v;
  69672. this._kernel = this._nearestBestKernel(v);
  69673. if (!this.blockCompilation) {
  69674. this._updateParameters();
  69675. }
  69676. },
  69677. enumerable: true,
  69678. configurable: true
  69679. });
  69680. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  69681. /**
  69682. * Gets wether or not the blur is unpacking/repacking floats
  69683. */
  69684. get: function () {
  69685. return this._packedFloat;
  69686. },
  69687. /**
  69688. * Sets wether or not the blur needs to unpack/repack floats
  69689. */
  69690. set: function (v) {
  69691. if (this._packedFloat === v) {
  69692. return;
  69693. }
  69694. this._packedFloat = v;
  69695. if (!this.blockCompilation) {
  69696. this._updateParameters();
  69697. }
  69698. },
  69699. enumerable: true,
  69700. configurable: true
  69701. });
  69702. /**
  69703. * Updates the effect with the current post process compile time values and recompiles the shader.
  69704. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  69705. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  69706. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  69707. * @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
  69708. * @param onCompiled Called when the shader has been compiled.
  69709. * @param onError Called if there is an error when compiling a shader.
  69710. */
  69711. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  69712. if (defines === void 0) { defines = null; }
  69713. if (uniforms === void 0) { uniforms = null; }
  69714. if (samplers === void 0) { samplers = null; }
  69715. this._updateParameters(onCompiled, onError);
  69716. };
  69717. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  69718. // Generate sampling offsets and weights
  69719. var N = this._kernel;
  69720. var centerIndex = (N - 1) / 2;
  69721. // Generate Gaussian sampling weights over kernel
  69722. var offsets = [];
  69723. var weights = [];
  69724. var totalWeight = 0;
  69725. for (var i = 0; i < N; i++) {
  69726. var u = i / (N - 1);
  69727. var w = this._gaussianWeight(u * 2.0 - 1);
  69728. offsets[i] = (i - centerIndex);
  69729. weights[i] = w;
  69730. totalWeight += w;
  69731. }
  69732. // Normalize weights
  69733. for (var i = 0; i < weights.length; i++) {
  69734. weights[i] /= totalWeight;
  69735. }
  69736. // Optimize: combine samples to take advantage of hardware linear sampling
  69737. // Walk from left to center, combining pairs (symmetrically)
  69738. var linearSamplingWeights = [];
  69739. var linearSamplingOffsets = [];
  69740. var linearSamplingMap = [];
  69741. for (var i = 0; i <= centerIndex; i += 2) {
  69742. var j = Math.min(i + 1, Math.floor(centerIndex));
  69743. var singleCenterSample = i === j;
  69744. if (singleCenterSample) {
  69745. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  69746. }
  69747. else {
  69748. var sharedCell = j === centerIndex;
  69749. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  69750. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  69751. if (offsetLinear === 0) {
  69752. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  69753. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  69754. }
  69755. else {
  69756. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  69757. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  69758. }
  69759. }
  69760. }
  69761. for (var i = 0; i < linearSamplingMap.length; i++) {
  69762. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  69763. linearSamplingWeights[i] = linearSamplingMap[i].w;
  69764. }
  69765. // Replace with optimized
  69766. offsets = linearSamplingOffsets;
  69767. weights = linearSamplingWeights;
  69768. // Generate shaders
  69769. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  69770. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  69771. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  69772. var defines = "";
  69773. defines += this._staticDefines;
  69774. for (var i = 0; i < varyingCount; i++) {
  69775. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  69776. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  69777. }
  69778. var depCount = 0;
  69779. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  69780. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  69781. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  69782. depCount++;
  69783. }
  69784. if (this.packedFloat) {
  69785. defines += "#define PACKEDFLOAT 1";
  69786. }
  69787. _super.prototype.updateEffect.call(this, defines, null, null, {
  69788. varyingCount: varyingCount,
  69789. depCount: depCount
  69790. }, onCompiled, onError);
  69791. };
  69792. /**
  69793. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  69794. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  69795. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  69796. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  69797. * The gaps between physical kernels are compensated for in the weighting of the samples
  69798. * @param idealKernel Ideal blur kernel.
  69799. * @return Nearest best kernel.
  69800. */
  69801. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  69802. var v = Math.round(idealKernel);
  69803. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  69804. var k = _a[_i];
  69805. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  69806. return Math.max(k, 3);
  69807. }
  69808. }
  69809. return Math.max(v, 3);
  69810. };
  69811. /**
  69812. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  69813. * @param x The point on the Gaussian distribution to sample.
  69814. * @return the value of the Gaussian function at x.
  69815. */
  69816. BlurPostProcess.prototype._gaussianWeight = function (x) {
  69817. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  69818. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  69819. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  69820. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  69821. // truncated at around 1.3% of peak strength.
  69822. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  69823. var sigma = (1 / 3);
  69824. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  69825. var exponent = -((x * x) / (2.0 * sigma * sigma));
  69826. var weight = (1.0 / denominator) * Math.exp(exponent);
  69827. return weight;
  69828. };
  69829. /**
  69830. * Generates a string that can be used as a floating point number in GLSL.
  69831. * @param x Value to print.
  69832. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  69833. * @return GLSL float string.
  69834. */
  69835. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  69836. if (decimalFigures === void 0) { decimalFigures = 8; }
  69837. return x.toFixed(decimalFigures).replace(/0+$/, '');
  69838. };
  69839. return BlurPostProcess;
  69840. }(BABYLON.PostProcess));
  69841. BABYLON.BlurPostProcess = BlurPostProcess;
  69842. })(BABYLON || (BABYLON = {}));
  69843. //# sourceMappingURL=babylon.blurPostProcess.js.map
  69844. "use strict";
  69845. var BABYLON;
  69846. (function (BABYLON) {
  69847. /**
  69848. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  69849. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  69850. * based on samples that have a large difference in distance than the center pixel.
  69851. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  69852. */
  69853. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  69854. __extends(DepthOfFieldBlurPostProcess, _super);
  69855. /**
  69856. * Creates a new instance of @see CircleOfConfusionPostProcess
  69857. * @param name The name of the effect.
  69858. * @param scene The scene the effect belongs to.
  69859. * @param direction The direction the blur should be applied.
  69860. * @param kernel The size of the kernel used to blur.
  69861. * @param options The required width/height ratio to downsize to before computing the render pass.
  69862. * @param camera The camera to apply the render pass to.
  69863. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  69864. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  69865. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69866. * @param engine The engine which the post process will be applied. (default: current engine)
  69867. * @param reusable If the post process can be reused on the same frame. (default: false)
  69868. * @param textureType Type of textures used when performing the post process. (default: 0)
  69869. * @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)
  69870. */
  69871. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  69872. if (imageToBlur === void 0) { imageToBlur = null; }
  69873. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  69874. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69875. if (blockCompilation === void 0) { blockCompilation = false; }
  69876. 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;
  69877. _this.direction = direction;
  69878. _this.onApplyObservable.add(function (effect) {
  69879. if (imageToBlur != null) {
  69880. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  69881. }
  69882. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  69883. if (scene.activeCamera) {
  69884. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  69885. }
  69886. });
  69887. return _this;
  69888. }
  69889. return DepthOfFieldBlurPostProcess;
  69890. }(BABYLON.BlurPostProcess));
  69891. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  69892. })(BABYLON || (BABYLON = {}));
  69893. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  69894. "use strict";
  69895. var BABYLON;
  69896. (function (BABYLON) {
  69897. /**
  69898. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  69899. */
  69900. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  69901. __extends(DepthOfFieldMergePostProcess, _super);
  69902. /**
  69903. * Creates a new instance of @see CircleOfConfusionPostProcess
  69904. * @param name The name of the effect.
  69905. * @param original The non-blurred image to be modified
  69906. * @param circleOfConfusion The circle of confusion post process that will determine how blurred each pixel should become.
  69907. * @param blurSteps Incrimental bluring post processes.
  69908. * @param options The required width/height ratio to downsize to before computing the render pass.
  69909. * @param camera The camera to apply the render pass to.
  69910. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69911. * @param engine The engine which the post process will be applied. (default: current engine)
  69912. * @param reusable If the post process can be reused on the same frame. (default: false)
  69913. * @param textureType Type of textures used when performing the post process. (default: 0)
  69914. * @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)
  69915. */
  69916. function DepthOfFieldMergePostProcess(name, original, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69917. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69918. if (blockCompilation === void 0) { blockCompilation = false; }
  69919. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  69920. _this.blurSteps = blurSteps;
  69921. _this.onApplyObservable.add(function (effect) {
  69922. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  69923. effect.setTextureFromPostProcess("textureSampler", original);
  69924. blurSteps.forEach(function (step, index) {
  69925. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  69926. });
  69927. });
  69928. if (!blockCompilation) {
  69929. _this.updateEffect();
  69930. }
  69931. return _this;
  69932. }
  69933. /**
  69934. * Updates the effect with the current post process compile time values and recompiles the shader.
  69935. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  69936. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  69937. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  69938. * @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
  69939. * @param onCompiled Called when the shader has been compiled.
  69940. * @param onError Called if there is an error when compiling a shader.
  69941. */
  69942. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  69943. if (defines === void 0) { defines = null; }
  69944. if (uniforms === void 0) { uniforms = null; }
  69945. if (samplers === void 0) { samplers = null; }
  69946. _super.prototype.updateEffect.call(this, defines ? defines : "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n", uniforms, samplers, indexParameters, onCompiled, onError);
  69947. };
  69948. return DepthOfFieldMergePostProcess;
  69949. }(BABYLON.PostProcess));
  69950. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  69951. })(BABYLON || (BABYLON = {}));
  69952. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  69953. "use strict";
  69954. var BABYLON;
  69955. (function (BABYLON) {
  69956. /**
  69957. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  69958. */
  69959. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  69960. __extends(CircleOfConfusionPostProcess, _super);
  69961. /**
  69962. * Creates a new instance of @see CircleOfConfusionPostProcess
  69963. * @param name The name of the effect.
  69964. * @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.
  69965. * @param options The required width/height ratio to downsize to before computing the render pass.
  69966. * @param camera The camera to apply the render pass to.
  69967. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  69968. * @param engine The engine which the post process will be applied. (default: current engine)
  69969. * @param reusable If the post process can be reused on the same frame. (default: false)
  69970. * @param textureType Type of textures used when performing the post process. (default: 0)
  69971. * @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)
  69972. */
  69973. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  69974. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  69975. if (blockCompilation === void 0) { blockCompilation = false; }
  69976. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  69977. /**
  69978. * 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.
  69979. */
  69980. _this.lensSize = 50;
  69981. /**
  69982. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  69983. */
  69984. _this.fStop = 1.4;
  69985. /**
  69986. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  69987. */
  69988. _this.focusDistance = 2000;
  69989. /**
  69990. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  69991. */
  69992. _this.focalLength = 50;
  69993. _this._depthTexture = null;
  69994. _this._depthTexture = depthTexture;
  69995. _this.onApplyObservable.add(function (effect) {
  69996. if (!_this._depthTexture) {
  69997. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  69998. return;
  69999. }
  70000. effect.setTexture("depthSampler", _this._depthTexture);
  70001. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  70002. var aperture = _this.lensSize / _this.fStop;
  70003. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  70004. effect.setFloat('focusDistance', _this.focusDistance);
  70005. effect.setFloat('cocPrecalculation', cocPrecalculation);
  70006. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  70007. });
  70008. return _this;
  70009. }
  70010. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  70011. /**
  70012. * 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.
  70013. */
  70014. set: function (value) {
  70015. this._depthTexture = value;
  70016. },
  70017. enumerable: true,
  70018. configurable: true
  70019. });
  70020. return CircleOfConfusionPostProcess;
  70021. }(BABYLON.PostProcess));
  70022. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  70023. })(BABYLON || (BABYLON = {}));
  70024. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  70025. "use strict";
  70026. var BABYLON;
  70027. (function (BABYLON) {
  70028. /**
  70029. * Specifies the level of max blur that should be applied when using the depth of field effect
  70030. */
  70031. var DepthOfFieldEffectBlurLevel;
  70032. (function (DepthOfFieldEffectBlurLevel) {
  70033. /**
  70034. * Subtle blur
  70035. */
  70036. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  70037. /**
  70038. * Medium blur
  70039. */
  70040. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  70041. /**
  70042. * Large blur
  70043. */
  70044. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  70045. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  70046. ;
  70047. /**
  70048. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  70049. */
  70050. var DepthOfFieldEffect = /** @class */ (function (_super) {
  70051. __extends(DepthOfFieldEffect, _super);
  70052. /**
  70053. * Creates a new instance of @see DepthOfFieldEffect
  70054. * @param scene The scene the effect belongs to.
  70055. * @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.
  70056. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  70057. * @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)
  70058. */
  70059. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  70060. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  70061. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  70062. if (blockCompilation === void 0) { blockCompilation = false; }
  70063. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  70064. return _this._effects;
  70065. }, true) || this;
  70066. _this._effects = [];
  70067. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  70068. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70069. // 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)
  70070. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  70071. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  70072. _this._depthOfFieldBlurY = [];
  70073. _this._depthOfFieldBlurX = [];
  70074. var blurCount = 1;
  70075. var kernelSize = 15;
  70076. switch (blurLevel) {
  70077. case DepthOfFieldEffectBlurLevel.High: {
  70078. blurCount = 3;
  70079. kernelSize = 51;
  70080. break;
  70081. }
  70082. case DepthOfFieldEffectBlurLevel.Medium: {
  70083. blurCount = 2;
  70084. kernelSize = 31;
  70085. break;
  70086. }
  70087. default: {
  70088. kernelSize = 15;
  70089. blurCount = 1;
  70090. break;
  70091. }
  70092. }
  70093. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  70094. for (var i = 0; i < blurCount; i++) {
  70095. var blurY = new BABYLON.DepthOfFieldBlurPostProcess("verticle blur", scene, new BABYLON.Vector2(0, 1.0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._circleOfConfusion, i == 0 ? _this._circleOfConfusion : null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70096. blurY.autoClear = false;
  70097. var blurX = new BABYLON.DepthOfFieldBlurPostProcess("horizontal blur", scene, new BABYLON.Vector2(1.0, 0), adjustedKernelSize, 1.0 / Math.pow(2, i), null, _this._circleOfConfusion, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70098. blurX.autoClear = false;
  70099. _this._depthOfFieldBlurY.push(blurY);
  70100. _this._depthOfFieldBlurX.push(blurX);
  70101. }
  70102. // Merge blurred images with original image based on circleOfConfusion
  70103. _this._depthOfFieldMerge = new BABYLON.DepthOfFieldMergePostProcess("depthOfFieldMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  70104. _this._depthOfFieldMerge.autoClear = false;
  70105. // Set all post processes on the effect.
  70106. _this._effects = [_this._circleOfConfusion];
  70107. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  70108. _this._effects.push(_this._depthOfFieldBlurY[i]);
  70109. _this._effects.push(_this._depthOfFieldBlurX[i]);
  70110. }
  70111. _this._effects.push(_this._depthOfFieldMerge);
  70112. return _this;
  70113. }
  70114. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  70115. get: function () {
  70116. return this._circleOfConfusion.focalLength;
  70117. },
  70118. /**
  70119. * The focal the length of the camera used in the effect
  70120. */
  70121. set: function (value) {
  70122. this._circleOfConfusion.focalLength = value;
  70123. },
  70124. enumerable: true,
  70125. configurable: true
  70126. });
  70127. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  70128. get: function () {
  70129. return this._circleOfConfusion.fStop;
  70130. },
  70131. /**
  70132. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  70133. */
  70134. set: function (value) {
  70135. this._circleOfConfusion.fStop = value;
  70136. },
  70137. enumerable: true,
  70138. configurable: true
  70139. });
  70140. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  70141. get: function () {
  70142. return this._circleOfConfusion.focusDistance;
  70143. },
  70144. /**
  70145. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  70146. */
  70147. set: function (value) {
  70148. this._circleOfConfusion.focusDistance = value;
  70149. },
  70150. enumerable: true,
  70151. configurable: true
  70152. });
  70153. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  70154. get: function () {
  70155. return this._circleOfConfusion.lensSize;
  70156. },
  70157. /**
  70158. * 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.
  70159. */
  70160. set: function (value) {
  70161. this._circleOfConfusion.lensSize = value;
  70162. },
  70163. enumerable: true,
  70164. configurable: true
  70165. });
  70166. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  70167. /**
  70168. * 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.
  70169. */
  70170. set: function (value) {
  70171. this._circleOfConfusion.depthTexture = value;
  70172. },
  70173. enumerable: true,
  70174. configurable: true
  70175. });
  70176. /**
  70177. * Disposes each of the internal effects for a given camera.
  70178. * @param camera The camera to dispose the effect on.
  70179. */
  70180. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  70181. this._circleOfConfusion.dispose(camera);
  70182. this._depthOfFieldBlurX.forEach(function (element) {
  70183. element.dispose(camera);
  70184. });
  70185. this._depthOfFieldBlurY.forEach(function (element) {
  70186. element.dispose(camera);
  70187. });
  70188. this._depthOfFieldMerge.dispose(camera);
  70189. };
  70190. /**
  70191. * Internal
  70192. */
  70193. DepthOfFieldEffect.prototype._updateEffects = function () {
  70194. for (var effect in this._effects) {
  70195. this._effects[effect].updateEffect();
  70196. }
  70197. };
  70198. /**
  70199. * Internal
  70200. * @returns if all the contained post processes are ready.
  70201. */
  70202. DepthOfFieldEffect.prototype._isReady = function () {
  70203. for (var effect in this._effects) {
  70204. if (!this._effects[effect].isReady()) {
  70205. return false;
  70206. }
  70207. }
  70208. return true;
  70209. };
  70210. return DepthOfFieldEffect;
  70211. }(BABYLON.PostProcessRenderEffect));
  70212. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  70213. })(BABYLON || (BABYLON = {}));
  70214. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  70215. "use strict";
  70216. var BABYLON;
  70217. (function (BABYLON) {
  70218. /**
  70219. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  70220. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  70221. */
  70222. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  70223. __extends(DefaultRenderingPipeline, _super);
  70224. /**
  70225. * @constructor
  70226. * @param {string} name - The rendering pipeline name
  70227. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  70228. * @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)
  70229. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  70230. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  70231. */
  70232. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  70233. if (automaticBuild === void 0) { automaticBuild = true; }
  70234. var _this = _super.call(this, scene.getEngine(), name) || this;
  70235. _this._originalCameras = [];
  70236. /**
  70237. * ID of the sharpen post process,
  70238. */
  70239. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  70240. /**
  70241. * ID of the pass post process used for bloom,
  70242. */
  70243. _this.PassPostProcessId = "PassPostProcessEffect";
  70244. /**
  70245. * ID of the highlight post process used for bloom,
  70246. */
  70247. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  70248. /**
  70249. * ID of the blurX post process used for bloom,
  70250. */
  70251. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  70252. /**
  70253. * ID of the blurY post process used for bloom,
  70254. */
  70255. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  70256. /**
  70257. * ID of the copy back post process used for bloom,
  70258. */
  70259. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  70260. /**
  70261. * ID of the image processing post process;
  70262. */
  70263. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  70264. /**
  70265. * ID of the Fast Approximate Anti-Aliasing post process;
  70266. */
  70267. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  70268. /**
  70269. * ID of the final merge post process;
  70270. */
  70271. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  70272. /**
  70273. * ID of the chromatic aberration post process,
  70274. */
  70275. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  70276. /**
  70277. * Animations which can be used to tweak settings over a period of time
  70278. */
  70279. _this.animations = [];
  70280. // Values
  70281. _this._sharpenEnabled = false;
  70282. _this._bloomEnabled = false;
  70283. _this._depthOfFieldEnabled = false;
  70284. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  70285. _this._fxaaEnabled = false;
  70286. _this._msaaEnabled = false;
  70287. _this._imageProcessingEnabled = true;
  70288. _this._bloomScale = 0.6;
  70289. _this._chromaticAberrationEnabled = false;
  70290. _this._buildAllowed = true;
  70291. /**
  70292. * Specifies the size of the bloom blur kernel, relative to the final output size
  70293. */
  70294. _this.bloomKernel = 64;
  70295. /**
  70296. * Specifies the weight of the bloom in the final rendering
  70297. */
  70298. _this._bloomWeight = 0.15;
  70299. _this._prevPostProcess = null;
  70300. _this._prevPrevPostProcess = null;
  70301. _this._cameras = cameras || [];
  70302. _this._originalCameras = _this._cameras.slice();
  70303. _this._buildAllowed = automaticBuild;
  70304. // Initialize
  70305. _this._scene = scene;
  70306. var caps = _this._scene.getEngine().getCaps();
  70307. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  70308. // Misc
  70309. if (_this._hdr) {
  70310. if (caps.textureHalfFloatRender) {
  70311. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  70312. }
  70313. else if (caps.textureFloatRender) {
  70314. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  70315. }
  70316. }
  70317. else {
  70318. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  70319. }
  70320. // Attach
  70321. scene.postProcessRenderPipelineManager.addPipeline(_this);
  70322. var engine = _this._scene.getEngine();
  70323. // Create post processes before hand so they can be modified before enabled.
  70324. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  70325. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  70326. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  70327. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  70328. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  70329. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  70330. _this._buildPipeline();
  70331. return _this;
  70332. }
  70333. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  70334. get: function () {
  70335. return this._sharpenEnabled;
  70336. },
  70337. /**
  70338. * Enable or disable the sharpen process from the pipeline
  70339. */
  70340. set: function (enabled) {
  70341. if (this._sharpenEnabled === enabled) {
  70342. return;
  70343. }
  70344. this._sharpenEnabled = enabled;
  70345. this._buildPipeline();
  70346. },
  70347. enumerable: true,
  70348. configurable: true
  70349. });
  70350. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  70351. get: function () {
  70352. return this._bloomWeight;
  70353. },
  70354. /**
  70355. * The strength of the bloom.
  70356. */
  70357. set: function (value) {
  70358. if (this._bloomWeight === value) {
  70359. return;
  70360. }
  70361. this._bloomWeight = value;
  70362. if (this._hdr && this.copyBack) {
  70363. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  70364. }
  70365. },
  70366. enumerable: true,
  70367. configurable: true
  70368. });
  70369. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  70370. get: function () {
  70371. return this._bloomScale;
  70372. },
  70373. /**
  70374. * The scale of the bloom, lower value will provide better performance.
  70375. */
  70376. set: function (value) {
  70377. if (this._bloomScale === value) {
  70378. return;
  70379. }
  70380. this._bloomScale = value;
  70381. this._buildPipeline();
  70382. },
  70383. enumerable: true,
  70384. configurable: true
  70385. });
  70386. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  70387. get: function () {
  70388. return this._bloomEnabled;
  70389. },
  70390. /**
  70391. * Enable or disable the bloom from the pipeline
  70392. */
  70393. set: function (enabled) {
  70394. if (this._bloomEnabled === enabled) {
  70395. return;
  70396. }
  70397. this._bloomEnabled = enabled;
  70398. this._buildPipeline();
  70399. },
  70400. enumerable: true,
  70401. configurable: true
  70402. });
  70403. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  70404. /**
  70405. * If the depth of field is enabled.
  70406. */
  70407. get: function () {
  70408. return this._depthOfFieldEnabled;
  70409. },
  70410. set: function (enabled) {
  70411. if (this._depthOfFieldEnabled === enabled) {
  70412. return;
  70413. }
  70414. this._depthOfFieldEnabled = enabled;
  70415. this._buildPipeline();
  70416. },
  70417. enumerable: true,
  70418. configurable: true
  70419. });
  70420. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  70421. /**
  70422. * Blur level of the depth of field effect. (Higher blur will effect performance)
  70423. */
  70424. get: function () {
  70425. return this._depthOfFieldBlurLevel;
  70426. },
  70427. set: function (value) {
  70428. if (this._depthOfFieldBlurLevel === value) {
  70429. return;
  70430. }
  70431. this._depthOfFieldBlurLevel = value;
  70432. // recreate dof and dispose old as this setting is not dynamic
  70433. var oldDof = this.depthOfField;
  70434. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType);
  70435. this.depthOfField.focalLength = oldDof.focalLength;
  70436. this.depthOfField.focusDistance = oldDof.focusDistance;
  70437. this.depthOfField.fStop = oldDof.fStop;
  70438. this.depthOfField.lensSize = oldDof.lensSize;
  70439. for (var i = 0; i < this._cameras.length; i++) {
  70440. oldDof.disposeEffects(this._cameras[i]);
  70441. }
  70442. this._buildPipeline();
  70443. },
  70444. enumerable: true,
  70445. configurable: true
  70446. });
  70447. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  70448. get: function () {
  70449. return this._fxaaEnabled;
  70450. },
  70451. /**
  70452. * If the anti aliasing is enabled.
  70453. */
  70454. set: function (enabled) {
  70455. if (this._fxaaEnabled === enabled) {
  70456. return;
  70457. }
  70458. this._fxaaEnabled = enabled;
  70459. this._buildPipeline();
  70460. },
  70461. enumerable: true,
  70462. configurable: true
  70463. });
  70464. Object.defineProperty(DefaultRenderingPipeline.prototype, "msaaEnabled", {
  70465. get: function () {
  70466. return this._msaaEnabled;
  70467. },
  70468. /**
  70469. * If the multisample anti-aliasing is enabled.
  70470. */
  70471. set: function (enabled) {
  70472. if (this._msaaEnabled === enabled) {
  70473. return;
  70474. }
  70475. this._msaaEnabled = enabled;
  70476. this._buildPipeline();
  70477. },
  70478. enumerable: true,
  70479. configurable: true
  70480. });
  70481. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  70482. get: function () {
  70483. return this._imageProcessingEnabled;
  70484. },
  70485. /**
  70486. * If image processing is enabled.
  70487. */
  70488. set: function (enabled) {
  70489. if (this._imageProcessingEnabled === enabled) {
  70490. return;
  70491. }
  70492. this._imageProcessingEnabled = enabled;
  70493. this._buildPipeline();
  70494. },
  70495. enumerable: true,
  70496. configurable: true
  70497. });
  70498. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  70499. get: function () {
  70500. return this._chromaticAberrationEnabled;
  70501. },
  70502. /**
  70503. * Enable or disable the chromaticAberration process from the pipeline
  70504. */
  70505. set: function (enabled) {
  70506. if (this._chromaticAberrationEnabled === enabled) {
  70507. return;
  70508. }
  70509. this._chromaticAberrationEnabled = enabled;
  70510. this._buildPipeline();
  70511. },
  70512. enumerable: true,
  70513. configurable: true
  70514. });
  70515. /**
  70516. * Force the compilation of the entire pipeline.
  70517. */
  70518. DefaultRenderingPipeline.prototype.prepare = function () {
  70519. var previousState = this._buildAllowed;
  70520. this._buildAllowed = true;
  70521. this._buildPipeline();
  70522. this._buildAllowed = previousState;
  70523. };
  70524. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  70525. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  70526. if (this._prevPostProcess && this._prevPostProcess.autoClear) {
  70527. postProcess.autoClear = false;
  70528. }
  70529. else {
  70530. postProcess.autoClear = true;
  70531. }
  70532. if (!skipTextureSharing) {
  70533. if (this._prevPrevPostProcess) {
  70534. postProcess.shareOutputWith(this._prevPrevPostProcess);
  70535. }
  70536. else {
  70537. postProcess.useOwnOutput();
  70538. }
  70539. if (this._prevPostProcess) {
  70540. this._prevPrevPostProcess = this._prevPostProcess;
  70541. }
  70542. this._prevPostProcess = postProcess;
  70543. }
  70544. };
  70545. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  70546. var _this = this;
  70547. if (!this._buildAllowed) {
  70548. return;
  70549. }
  70550. var engine = this._scene.getEngine();
  70551. this._disposePostProcesses();
  70552. if (this._cameras !== null) {
  70553. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  70554. // get back cameras to be used to reattach pipeline
  70555. this._cameras = this._originalCameras.slice();
  70556. }
  70557. this._reset();
  70558. this._prevPostProcess = null;
  70559. this._prevPrevPostProcess = null;
  70560. if (this.sharpenEnabled) {
  70561. if (!this.sharpen.isReady()) {
  70562. this.sharpen.updateEffect();
  70563. }
  70564. this.addEffect(this._sharpenEffect);
  70565. this._setAutoClearAndTextureSharing(this.sharpen);
  70566. }
  70567. if (this.depthOfFieldEnabled) {
  70568. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  70569. this.depthOfField.depthTexture = depthTexture;
  70570. if (!this.depthOfField._isReady()) {
  70571. this.depthOfField._updateEffects();
  70572. }
  70573. this.addEffect(this.depthOfField);
  70574. this._setAutoClearAndTextureSharing(this.depthOfField._depthOfFieldMerge);
  70575. }
  70576. if (this.bloomEnabled) {
  70577. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70578. this._setAutoClearAndTextureSharing(this.pass, true);
  70579. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  70580. if (!this._hdr) {
  70581. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70582. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  70583. this.highlights.autoClear = false;
  70584. this.highlights.alwaysForcePOT = true;
  70585. }
  70586. this.blurX = new BABYLON.BlurPostProcess("horizontal blur", new BABYLON.Vector2(1.0, 0), 10.0, this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70587. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  70588. this.blurX.alwaysForcePOT = true;
  70589. this.blurX.autoClear = false;
  70590. this.blurX.onActivateObservable.add(function () {
  70591. var dw = _this.blurX.width / engine.getRenderWidth(true);
  70592. _this.blurX.kernel = _this.bloomKernel * dw;
  70593. });
  70594. this.blurY = new BABYLON.BlurPostProcess("vertical blur", new BABYLON.Vector2(0, 1.0), 10.0, this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70595. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  70596. this.blurY.alwaysForcePOT = true;
  70597. this.blurY.autoClear = false;
  70598. this.blurY.onActivateObservable.add(function () {
  70599. var dh = _this.blurY.height / engine.getRenderHeight(true);
  70600. _this.blurY.kernel = _this.bloomKernel * dh;
  70601. });
  70602. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70603. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  70604. this.copyBack.alwaysForcePOT = true;
  70605. if (this._hdr) {
  70606. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  70607. var w = this.bloomWeight;
  70608. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  70609. }
  70610. else {
  70611. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  70612. }
  70613. this.copyBack.autoClear = false;
  70614. }
  70615. if (this._imageProcessingEnabled) {
  70616. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70617. if (this._hdr) {
  70618. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  70619. }
  70620. else {
  70621. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  70622. }
  70623. }
  70624. if (this._hdr && this.imageProcessing) {
  70625. this.finalMerge = this.imageProcessing;
  70626. }
  70627. else {
  70628. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70629. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  70630. this._setAutoClearAndTextureSharing(this.finalMerge, true);
  70631. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  70632. }
  70633. if (this.bloomEnabled) {
  70634. if (this._hdr) {
  70635. this.copyBack.shareOutputWith(this.blurX);
  70636. if (this.imageProcessing) {
  70637. this.imageProcessing.shareOutputWith(this.pass);
  70638. this.imageProcessing.autoClear = false;
  70639. }
  70640. else {
  70641. this.finalMerge.shareOutputWith(this.pass);
  70642. }
  70643. }
  70644. else {
  70645. this.finalMerge.shareOutputWith(this.pass);
  70646. }
  70647. }
  70648. if (this.fxaaEnabled) {
  70649. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  70650. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  70651. this._setAutoClearAndTextureSharing(this.fxaa);
  70652. }
  70653. if (this.chromaticAberrationEnabled) {
  70654. if (!this.chromaticAberration.isReady()) {
  70655. this.chromaticAberration.updateEffect();
  70656. }
  70657. this.addEffect(this._chromaticAberrationEffect);
  70658. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  70659. }
  70660. if (this._cameras !== null) {
  70661. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  70662. }
  70663. if (this.msaaEnabled) {
  70664. if (!this._enableMSAAOnFirstPostProcess()) {
  70665. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  70666. }
  70667. }
  70668. };
  70669. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  70670. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  70671. for (var i = 0; i < this._cameras.length; i++) {
  70672. var camera = this._cameras[i];
  70673. if (this.pass) {
  70674. this.pass.dispose(camera);
  70675. }
  70676. if (this.highlights) {
  70677. this.highlights.dispose(camera);
  70678. }
  70679. if (this.blurX) {
  70680. this.blurX.dispose(camera);
  70681. }
  70682. if (this.blurY) {
  70683. this.blurY.dispose(camera);
  70684. }
  70685. if (this.copyBack) {
  70686. this.copyBack.dispose(camera);
  70687. }
  70688. if (this.imageProcessing) {
  70689. this.imageProcessing.dispose(camera);
  70690. }
  70691. if (this.fxaa) {
  70692. this.fxaa.dispose(camera);
  70693. }
  70694. if (this.finalMerge) {
  70695. this.finalMerge.dispose(camera);
  70696. }
  70697. // These are created in the constructor and should not be disposed on every pipeline change
  70698. if (disposeNonRecreated) {
  70699. if (this.sharpen) {
  70700. this.sharpen.dispose(camera);
  70701. }
  70702. if (this.depthOfField) {
  70703. this.depthOfField.disposeEffects(camera);
  70704. }
  70705. if (this.chromaticAberration) {
  70706. this.chromaticAberration.dispose(camera);
  70707. }
  70708. }
  70709. }
  70710. this.pass = null;
  70711. this.highlights = null;
  70712. this.blurX = null;
  70713. this.blurY = null;
  70714. this.copyBack = null;
  70715. this.imageProcessing = null;
  70716. this.fxaa = null;
  70717. this.finalMerge = null;
  70718. if (disposeNonRecreated) {
  70719. this.sharpen = null;
  70720. this.depthOfField = null;
  70721. this.chromaticAberration = null;
  70722. }
  70723. };
  70724. /**
  70725. * Dispose of the pipeline and stop all post processes
  70726. */
  70727. DefaultRenderingPipeline.prototype.dispose = function () {
  70728. this._disposePostProcesses(true);
  70729. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  70730. _super.prototype.dispose.call(this);
  70731. };
  70732. /**
  70733. * Serialize the rendering pipeline (Used when exporting)
  70734. * @returns the serialized object
  70735. */
  70736. DefaultRenderingPipeline.prototype.serialize = function () {
  70737. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  70738. serializationObject.customType = "DefaultRenderingPipeline";
  70739. return serializationObject;
  70740. };
  70741. /**
  70742. * Parse the serialized pipeline
  70743. * @param source Source pipeline.
  70744. * @param scene The scene to load the pipeline to.
  70745. * @param rootUrl The URL of the serialized pipeline.
  70746. * @returns An instantiated pipeline from the serialized object.
  70747. */
  70748. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  70749. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  70750. };
  70751. __decorate([
  70752. BABYLON.serialize()
  70753. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  70754. __decorate([
  70755. BABYLON.serialize()
  70756. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  70757. __decorate([
  70758. BABYLON.serialize()
  70759. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  70760. __decorate([
  70761. BABYLON.serialize()
  70762. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  70763. __decorate([
  70764. BABYLON.serialize()
  70765. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  70766. __decorate([
  70767. BABYLON.serialize()
  70768. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  70769. __decorate([
  70770. BABYLON.serialize()
  70771. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  70772. __decorate([
  70773. BABYLON.serialize()
  70774. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  70775. __decorate([
  70776. BABYLON.serialize()
  70777. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  70778. __decorate([
  70779. BABYLON.serialize()
  70780. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  70781. __decorate([
  70782. BABYLON.serialize()
  70783. ], DefaultRenderingPipeline.prototype, "msaaEnabled", null);
  70784. __decorate([
  70785. BABYLON.serialize()
  70786. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  70787. __decorate([
  70788. BABYLON.serialize()
  70789. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  70790. return DefaultRenderingPipeline;
  70791. }(BABYLON.PostProcessRenderPipeline));
  70792. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  70793. })(BABYLON || (BABYLON = {}));
  70794. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  70795. "use strict";
  70796. var BABYLON;
  70797. (function (BABYLON) {
  70798. /**
  70799. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  70800. */
  70801. var GeometryBufferRenderer = /** @class */ (function () {
  70802. /**
  70803. * Creates a new G Buffer for the scene. @see GeometryBufferRenderer
  70804. * @param scene The scene the buffer belongs to
  70805. * @param ratio How big is the buffer related to the main canvas.
  70806. */
  70807. function GeometryBufferRenderer(scene, ratio) {
  70808. if (ratio === void 0) { ratio = 1; }
  70809. this._enablePosition = false;
  70810. this._scene = scene;
  70811. this._ratio = ratio;
  70812. // Render target
  70813. this._createRenderTargets();
  70814. }
  70815. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  70816. /**
  70817. * Set the render list (meshes to be rendered) used in the G buffer.
  70818. */
  70819. set: function (meshes) {
  70820. this._multiRenderTarget.renderList = meshes;
  70821. },
  70822. enumerable: true,
  70823. configurable: true
  70824. });
  70825. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  70826. /**
  70827. * Gets wether or not G buffer are supported by the running hardware.
  70828. * This requires draw buffer supports
  70829. */
  70830. get: function () {
  70831. return this._multiRenderTarget.isSupported;
  70832. },
  70833. enumerable: true,
  70834. configurable: true
  70835. });
  70836. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  70837. /**
  70838. * Gets wether or not position are enabled for the G buffer.
  70839. */
  70840. get: function () {
  70841. return this._enablePosition;
  70842. },
  70843. /**
  70844. * Sets wether or not position are enabled for the G buffer.
  70845. */
  70846. set: function (enable) {
  70847. this._enablePosition = enable;
  70848. this.dispose();
  70849. this._createRenderTargets();
  70850. },
  70851. enumerable: true,
  70852. configurable: true
  70853. });
  70854. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  70855. /**
  70856. * Gets the scene associated with the buffer.
  70857. */
  70858. get: function () {
  70859. return this._scene;
  70860. },
  70861. enumerable: true,
  70862. configurable: true
  70863. });
  70864. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  70865. /**
  70866. * Gets the ratio used by the buffer during its creation.
  70867. * How big is the buffer related to the main canvas.
  70868. */
  70869. get: function () {
  70870. return this._ratio;
  70871. },
  70872. enumerable: true,
  70873. configurable: true
  70874. });
  70875. /**
  70876. * Checks wether everything is ready to render a submesh to the G buffer.
  70877. * @param subMesh the submesh to check readiness for
  70878. * @param useInstances is the mesh drawn using instance or not
  70879. * @returns true if ready otherwise false
  70880. */
  70881. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  70882. var material = subMesh.getMaterial();
  70883. if (material && material.disableDepthWrite) {
  70884. return false;
  70885. }
  70886. var defines = [];
  70887. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  70888. var mesh = subMesh.getMesh();
  70889. // Alpha test
  70890. if (material && material.needAlphaTesting()) {
  70891. defines.push("#define ALPHATEST");
  70892. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  70893. attribs.push(BABYLON.VertexBuffer.UVKind);
  70894. defines.push("#define UV1");
  70895. }
  70896. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  70897. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  70898. defines.push("#define UV2");
  70899. }
  70900. }
  70901. // Buffers
  70902. if (this._enablePosition) {
  70903. defines.push("#define POSITION");
  70904. }
  70905. // Bones
  70906. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  70907. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  70908. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  70909. if (mesh.numBoneInfluencers > 4) {
  70910. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  70911. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  70912. }
  70913. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  70914. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  70915. }
  70916. else {
  70917. defines.push("#define NUM_BONE_INFLUENCERS 0");
  70918. }
  70919. // Instances
  70920. if (useInstances) {
  70921. defines.push("#define INSTANCES");
  70922. attribs.push("world0");
  70923. attribs.push("world1");
  70924. attribs.push("world2");
  70925. attribs.push("world3");
  70926. }
  70927. // Get correct effect
  70928. var join = defines.join("\n");
  70929. if (this._cachedDefines !== join) {
  70930. this._cachedDefines = join;
  70931. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  70932. }
  70933. return this._effect.isReady();
  70934. };
  70935. /**
  70936. * Gets the current underlying G Buffer.
  70937. * @returns the buffer
  70938. */
  70939. GeometryBufferRenderer.prototype.getGBuffer = function () {
  70940. return this._multiRenderTarget;
  70941. };
  70942. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  70943. /**
  70944. * Gets the number of samples used to render the buffer (anti aliasing).
  70945. */
  70946. get: function () {
  70947. return this._multiRenderTarget.samples;
  70948. },
  70949. /**
  70950. * Sets the number of samples used to render the buffer (anti aliasing).
  70951. */
  70952. set: function (value) {
  70953. this._multiRenderTarget.samples = value;
  70954. },
  70955. enumerable: true,
  70956. configurable: true
  70957. });
  70958. /**
  70959. * Disposes the renderer and frees up associated resources.
  70960. */
  70961. GeometryBufferRenderer.prototype.dispose = function () {
  70962. this.getGBuffer().dispose();
  70963. };
  70964. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  70965. var _this = this;
  70966. var engine = this._scene.getEngine();
  70967. var count = this._enablePosition ? 3 : 2;
  70968. 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 });
  70969. if (!this.isSupported) {
  70970. return;
  70971. }
  70972. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70973. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  70974. this._multiRenderTarget.refreshRate = 1;
  70975. this._multiRenderTarget.renderParticles = false;
  70976. this._multiRenderTarget.renderList = null;
  70977. // set default depth value to 1.0 (far away)
  70978. this._multiRenderTarget.onClearObservable.add(function (engine) {
  70979. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  70980. });
  70981. // Custom render function
  70982. var renderSubMesh = function (subMesh) {
  70983. var mesh = subMesh.getRenderingMesh();
  70984. var scene = _this._scene;
  70985. var engine = scene.getEngine();
  70986. var material = subMesh.getMaterial();
  70987. if (!material) {
  70988. return;
  70989. }
  70990. // Culling
  70991. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  70992. // Managing instances
  70993. var batch = mesh._getInstancesRenderList(subMesh._id);
  70994. if (batch.mustReturn) {
  70995. return;
  70996. }
  70997. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  70998. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  70999. engine.enableEffect(_this._effect);
  71000. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  71001. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  71002. _this._effect.setMatrix("view", scene.getViewMatrix());
  71003. // Alpha test
  71004. if (material && material.needAlphaTesting()) {
  71005. var alphaTexture = material.getAlphaTestTexture();
  71006. if (alphaTexture) {
  71007. _this._effect.setTexture("diffuseSampler", alphaTexture);
  71008. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  71009. }
  71010. }
  71011. // Bones
  71012. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  71013. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  71014. }
  71015. // Draw
  71016. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  71017. }
  71018. };
  71019. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  71020. var index;
  71021. if (depthOnlySubMeshes.length) {
  71022. engine.setColorWrite(false);
  71023. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  71024. renderSubMesh(depthOnlySubMeshes.data[index]);
  71025. }
  71026. engine.setColorWrite(true);
  71027. }
  71028. for (index = 0; index < opaqueSubMeshes.length; index++) {
  71029. renderSubMesh(opaqueSubMeshes.data[index]);
  71030. }
  71031. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  71032. renderSubMesh(alphaTestSubMeshes.data[index]);
  71033. }
  71034. };
  71035. };
  71036. return GeometryBufferRenderer;
  71037. }());
  71038. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  71039. })(BABYLON || (BABYLON = {}));
  71040. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  71041. "use strict";
  71042. var BABYLON;
  71043. (function (BABYLON) {
  71044. var RefractionPostProcess = /** @class */ (function (_super) {
  71045. __extends(RefractionPostProcess, _super);
  71046. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  71047. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  71048. _this.color = color;
  71049. _this.depth = depth;
  71050. _this.colorLevel = colorLevel;
  71051. _this._ownRefractionTexture = true;
  71052. _this.onActivateObservable.add(function (cam) {
  71053. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  71054. });
  71055. _this.onApplyObservable.add(function (effect) {
  71056. effect.setColor3("baseColor", _this.color);
  71057. effect.setFloat("depth", _this.depth);
  71058. effect.setFloat("colorLevel", _this.colorLevel);
  71059. effect.setTexture("refractionSampler", _this._refTexture);
  71060. });
  71061. return _this;
  71062. }
  71063. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  71064. /**
  71065. * Gets or sets the refraction texture
  71066. * Please note that you are responsible for disposing the texture if you set it manually
  71067. */
  71068. get: function () {
  71069. return this._refTexture;
  71070. },
  71071. set: function (value) {
  71072. if (this._refTexture && this._ownRefractionTexture) {
  71073. this._refTexture.dispose();
  71074. }
  71075. this._refTexture = value;
  71076. this._ownRefractionTexture = false;
  71077. },
  71078. enumerable: true,
  71079. configurable: true
  71080. });
  71081. // Methods
  71082. RefractionPostProcess.prototype.dispose = function (camera) {
  71083. if (this._refTexture && this._ownRefractionTexture) {
  71084. this._refTexture.dispose();
  71085. this._refTexture = null;
  71086. }
  71087. _super.prototype.dispose.call(this, camera);
  71088. };
  71089. return RefractionPostProcess;
  71090. }(BABYLON.PostProcess));
  71091. BABYLON.RefractionPostProcess = RefractionPostProcess;
  71092. })(BABYLON || (BABYLON = {}));
  71093. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  71094. "use strict";
  71095. var BABYLON;
  71096. (function (BABYLON) {
  71097. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  71098. __extends(BlackAndWhitePostProcess, _super);
  71099. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  71100. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  71101. _this.degree = 1;
  71102. _this.onApplyObservable.add(function (effect) {
  71103. effect.setFloat("degree", _this.degree);
  71104. });
  71105. return _this;
  71106. }
  71107. return BlackAndWhitePostProcess;
  71108. }(BABYLON.PostProcess));
  71109. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  71110. })(BABYLON || (BABYLON = {}));
  71111. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  71112. "use strict";
  71113. var BABYLON;
  71114. (function (BABYLON) {
  71115. /**
  71116. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  71117. * input texture to perform effects such as edge detection or sharpening
  71118. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  71119. */
  71120. var ConvolutionPostProcess = /** @class */ (function (_super) {
  71121. __extends(ConvolutionPostProcess, _super);
  71122. /**
  71123. * Creates a new instance of @see ConvolutionPostProcess
  71124. * @param name The name of the effect.
  71125. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  71126. * @param options The required width/height ratio to downsize to before computing the render pass.
  71127. * @param camera The camera to apply the render pass to.
  71128. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  71129. * @param engine The engine which the post process will be applied. (default: current engine)
  71130. * @param reusable If the post process can be reused on the same frame. (default: false)
  71131. * @param textureType Type of textures used when performing the post process. (default: 0)
  71132. */
  71133. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  71134. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71135. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  71136. _this.kernel = kernel;
  71137. _this.onApply = function (effect) {
  71138. effect.setFloat2("screenSize", _this.width, _this.height);
  71139. effect.setArray("kernel", _this.kernel);
  71140. };
  71141. return _this;
  71142. }
  71143. // Statics
  71144. /**
  71145. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71146. */
  71147. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  71148. /**
  71149. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71150. */
  71151. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  71152. /**
  71153. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71154. */
  71155. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  71156. /**
  71157. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71158. */
  71159. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  71160. /**
  71161. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71162. */
  71163. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  71164. /**
  71165. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  71166. */
  71167. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  71168. return ConvolutionPostProcess;
  71169. }(BABYLON.PostProcess));
  71170. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  71171. })(BABYLON || (BABYLON = {}));
  71172. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  71173. "use strict";
  71174. var BABYLON;
  71175. (function (BABYLON) {
  71176. var FilterPostProcess = /** @class */ (function (_super) {
  71177. __extends(FilterPostProcess, _super);
  71178. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  71179. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  71180. _this.kernelMatrix = kernelMatrix;
  71181. _this.onApply = function (effect) {
  71182. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  71183. };
  71184. return _this;
  71185. }
  71186. return FilterPostProcess;
  71187. }(BABYLON.PostProcess));
  71188. BABYLON.FilterPostProcess = FilterPostProcess;
  71189. })(BABYLON || (BABYLON = {}));
  71190. //# sourceMappingURL=babylon.filterPostProcess.js.map
  71191. "use strict";
  71192. var BABYLON;
  71193. (function (BABYLON) {
  71194. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  71195. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  71196. __extends(VolumetricLightScatteringPostProcess, _super);
  71197. /**
  71198. * @constructor
  71199. * @param {string} name - The post-process name
  71200. * @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)
  71201. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  71202. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  71203. * @param {number} samples - The post-process quality, default 100
  71204. * @param {number} samplingMode - The post-process filtering mode
  71205. * @param {BABYLON.Engine} engine - The babylon engine
  71206. * @param {boolean} reusable - If the post-process is reusable
  71207. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  71208. */
  71209. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  71210. if (samples === void 0) { samples = 100; }
  71211. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  71212. 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;
  71213. _this._screenCoordinates = BABYLON.Vector2.Zero();
  71214. /**
  71215. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  71216. * @type {Vector3}
  71217. */
  71218. _this.customMeshPosition = BABYLON.Vector3.Zero();
  71219. /**
  71220. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  71221. * @type {boolean}
  71222. */
  71223. _this.useCustomMeshPosition = false;
  71224. /**
  71225. * If the post-process should inverse the light scattering direction
  71226. * @type {boolean}
  71227. */
  71228. _this.invert = true;
  71229. /**
  71230. * Array containing the excluded meshes not rendered in the internal pass
  71231. */
  71232. _this.excludedMeshes = new Array();
  71233. /**
  71234. * Controls the overall intensity of the post-process
  71235. * @type {number}
  71236. */
  71237. _this.exposure = 0.3;
  71238. /**
  71239. * Dissipates each sample's contribution in range [0, 1]
  71240. * @type {number}
  71241. */
  71242. _this.decay = 0.96815;
  71243. /**
  71244. * Controls the overall intensity of each sample
  71245. * @type {number}
  71246. */
  71247. _this.weight = 0.58767;
  71248. /**
  71249. * Controls the density of each sample
  71250. * @type {number}
  71251. */
  71252. _this.density = 0.926;
  71253. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  71254. engine = scene.getEngine();
  71255. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  71256. // Configure mesh
  71257. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  71258. // Configure
  71259. _this._createPass(scene, ratio.passRatio || ratio);
  71260. _this.onActivate = function (camera) {
  71261. if (!_this.isSupported) {
  71262. _this.dispose(camera);
  71263. }
  71264. _this.onActivate = null;
  71265. };
  71266. _this.onApplyObservable.add(function (effect) {
  71267. _this._updateMeshScreenCoordinates(scene);
  71268. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  71269. effect.setFloat("exposure", _this.exposure);
  71270. effect.setFloat("decay", _this.decay);
  71271. effect.setFloat("weight", _this.weight);
  71272. effect.setFloat("density", _this.density);
  71273. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  71274. });
  71275. return _this;
  71276. }
  71277. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  71278. get: function () {
  71279. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  71280. return false;
  71281. },
  71282. set: function (useDiffuseColor) {
  71283. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  71284. },
  71285. enumerable: true,
  71286. configurable: true
  71287. });
  71288. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  71289. return "VolumetricLightScatteringPostProcess";
  71290. };
  71291. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  71292. var mesh = subMesh.getMesh();
  71293. // Render this.mesh as default
  71294. if (mesh === this.mesh && mesh.material) {
  71295. return mesh.material.isReady(mesh);
  71296. }
  71297. var defines = [];
  71298. var attribs = [BABYLON.VertexBuffer.PositionKind];
  71299. var material = subMesh.getMaterial();
  71300. // Alpha test
  71301. if (material) {
  71302. if (material.needAlphaTesting()) {
  71303. defines.push("#define ALPHATEST");
  71304. }
  71305. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  71306. attribs.push(BABYLON.VertexBuffer.UVKind);
  71307. defines.push("#define UV1");
  71308. }
  71309. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  71310. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  71311. defines.push("#define UV2");
  71312. }
  71313. }
  71314. // Bones
  71315. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  71316. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  71317. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  71318. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  71319. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  71320. }
  71321. else {
  71322. defines.push("#define NUM_BONE_INFLUENCERS 0");
  71323. }
  71324. // Instances
  71325. if (useInstances) {
  71326. defines.push("#define INSTANCES");
  71327. attribs.push("world0");
  71328. attribs.push("world1");
  71329. attribs.push("world2");
  71330. attribs.push("world3");
  71331. }
  71332. // Get correct effect
  71333. var join = defines.join("\n");
  71334. if (this._cachedDefines !== join) {
  71335. this._cachedDefines = join;
  71336. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  71337. }
  71338. return this._volumetricLightScatteringPass.isReady();
  71339. };
  71340. /**
  71341. * Sets the new light position for light scattering effect
  71342. * @param {BABYLON.Vector3} The new custom light position
  71343. */
  71344. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  71345. this.customMeshPosition = position;
  71346. };
  71347. /**
  71348. * Returns the light position for light scattering effect
  71349. * @return {BABYLON.Vector3} The custom light position
  71350. */
  71351. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  71352. return this.customMeshPosition;
  71353. };
  71354. /**
  71355. * Disposes the internal assets and detaches the post-process from the camera
  71356. */
  71357. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  71358. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  71359. if (rttIndex !== -1) {
  71360. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  71361. }
  71362. this._volumetricLightScatteringRTT.dispose();
  71363. _super.prototype.dispose.call(this, camera);
  71364. };
  71365. /**
  71366. * Returns the render target texture used by the post-process
  71367. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  71368. */
  71369. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  71370. return this._volumetricLightScatteringRTT;
  71371. };
  71372. // Private methods
  71373. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  71374. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  71375. return true;
  71376. }
  71377. return false;
  71378. };
  71379. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  71380. var _this = this;
  71381. var engine = scene.getEngine();
  71382. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  71383. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71384. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71385. this._volumetricLightScatteringRTT.renderList = null;
  71386. this._volumetricLightScatteringRTT.renderParticles = false;
  71387. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  71388. var camera = this.getCamera();
  71389. if (camera) {
  71390. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  71391. }
  71392. else {
  71393. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  71394. }
  71395. // Custom render function for submeshes
  71396. var renderSubMesh = function (subMesh) {
  71397. var mesh = subMesh.getRenderingMesh();
  71398. if (_this._meshExcluded(mesh)) {
  71399. return;
  71400. }
  71401. var material = subMesh.getMaterial();
  71402. if (!material) {
  71403. return;
  71404. }
  71405. var scene = mesh.getScene();
  71406. var engine = scene.getEngine();
  71407. // Culling
  71408. engine.setState(material.backFaceCulling);
  71409. // Managing instances
  71410. var batch = mesh._getInstancesRenderList(subMesh._id);
  71411. if (batch.mustReturn) {
  71412. return;
  71413. }
  71414. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  71415. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  71416. var effect = _this._volumetricLightScatteringPass;
  71417. if (mesh === _this.mesh) {
  71418. if (subMesh.effect) {
  71419. effect = subMesh.effect;
  71420. }
  71421. else {
  71422. effect = material.getEffect();
  71423. }
  71424. }
  71425. engine.enableEffect(effect);
  71426. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  71427. if (mesh === _this.mesh) {
  71428. material.bind(mesh.getWorldMatrix(), mesh);
  71429. }
  71430. else {
  71431. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  71432. // Alpha test
  71433. if (material && material.needAlphaTesting()) {
  71434. var alphaTexture = material.getAlphaTestTexture();
  71435. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  71436. if (alphaTexture) {
  71437. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  71438. }
  71439. }
  71440. // Bones
  71441. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  71442. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  71443. }
  71444. }
  71445. // Draw
  71446. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  71447. }
  71448. };
  71449. // Render target texture callbacks
  71450. var savedSceneClearColor;
  71451. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  71452. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  71453. savedSceneClearColor = scene.clearColor;
  71454. scene.clearColor = sceneClearColor;
  71455. });
  71456. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  71457. scene.clearColor = savedSceneClearColor;
  71458. });
  71459. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  71460. var engine = scene.getEngine();
  71461. var index;
  71462. if (depthOnlySubMeshes.length) {
  71463. engine.setColorWrite(false);
  71464. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  71465. renderSubMesh(depthOnlySubMeshes.data[index]);
  71466. }
  71467. engine.setColorWrite(true);
  71468. }
  71469. for (index = 0; index < opaqueSubMeshes.length; index++) {
  71470. renderSubMesh(opaqueSubMeshes.data[index]);
  71471. }
  71472. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  71473. renderSubMesh(alphaTestSubMeshes.data[index]);
  71474. }
  71475. if (transparentSubMeshes.length) {
  71476. // Sort sub meshes
  71477. for (index = 0; index < transparentSubMeshes.length; index++) {
  71478. var submesh = transparentSubMeshes.data[index];
  71479. var boundingInfo = submesh.getBoundingInfo();
  71480. if (boundingInfo && scene.activeCamera) {
  71481. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  71482. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  71483. }
  71484. }
  71485. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  71486. sortedArray.sort(function (a, b) {
  71487. // Alpha index first
  71488. if (a._alphaIndex > b._alphaIndex) {
  71489. return 1;
  71490. }
  71491. if (a._alphaIndex < b._alphaIndex) {
  71492. return -1;
  71493. }
  71494. // Then distance to camera
  71495. if (a._distanceToCamera < b._distanceToCamera) {
  71496. return 1;
  71497. }
  71498. if (a._distanceToCamera > b._distanceToCamera) {
  71499. return -1;
  71500. }
  71501. return 0;
  71502. });
  71503. // Render sub meshes
  71504. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  71505. for (index = 0; index < sortedArray.length; index++) {
  71506. renderSubMesh(sortedArray[index]);
  71507. }
  71508. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  71509. }
  71510. };
  71511. };
  71512. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  71513. var transform = scene.getTransformMatrix();
  71514. var meshPosition;
  71515. if (this.useCustomMeshPosition) {
  71516. meshPosition = this.customMeshPosition;
  71517. }
  71518. else if (this.attachedNode) {
  71519. meshPosition = this.attachedNode.position;
  71520. }
  71521. else {
  71522. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  71523. }
  71524. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  71525. this._screenCoordinates.x = pos.x / this._viewPort.width;
  71526. this._screenCoordinates.y = pos.y / this._viewPort.height;
  71527. if (this.invert)
  71528. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  71529. };
  71530. // Static methods
  71531. /**
  71532. * Creates a default mesh for the Volumeric Light Scattering post-process
  71533. * @param {string} The mesh name
  71534. * @param {BABYLON.Scene} The scene where to create the mesh
  71535. * @return {BABYLON.Mesh} the default mesh
  71536. */
  71537. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  71538. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  71539. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  71540. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  71541. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  71542. mesh.material = material;
  71543. return mesh;
  71544. };
  71545. __decorate([
  71546. BABYLON.serializeAsVector3()
  71547. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  71548. __decorate([
  71549. BABYLON.serialize()
  71550. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  71551. __decorate([
  71552. BABYLON.serialize()
  71553. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  71554. __decorate([
  71555. BABYLON.serializeAsMeshReference()
  71556. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  71557. __decorate([
  71558. BABYLON.serialize()
  71559. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  71560. __decorate([
  71561. BABYLON.serialize()
  71562. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  71563. __decorate([
  71564. BABYLON.serialize()
  71565. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  71566. __decorate([
  71567. BABYLON.serialize()
  71568. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  71569. __decorate([
  71570. BABYLON.serialize()
  71571. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  71572. return VolumetricLightScatteringPostProcess;
  71573. }(BABYLON.PostProcess));
  71574. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  71575. })(BABYLON || (BABYLON = {}));
  71576. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  71577. "use strict";
  71578. //
  71579. // This post-process allows the modification of rendered colors by using
  71580. // a 'look-up table' (LUT). This effect is also called Color Grading.
  71581. //
  71582. // The object needs to be provided an url to a texture containing the color
  71583. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  71584. // Use an image editing software to tweak the LUT to match your needs.
  71585. //
  71586. // For an example of a color LUT, see here:
  71587. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  71588. // For explanations on color grading, see here:
  71589. // http://udn.epicgames.com/Three/ColorGrading.html
  71590. //
  71591. var BABYLON;
  71592. (function (BABYLON) {
  71593. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  71594. __extends(ColorCorrectionPostProcess, _super);
  71595. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  71596. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  71597. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  71598. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  71599. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71600. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71601. _this.onApply = function (effect) {
  71602. effect.setTexture("colorTable", _this._colorTableTexture);
  71603. };
  71604. return _this;
  71605. }
  71606. return ColorCorrectionPostProcess;
  71607. }(BABYLON.PostProcess));
  71608. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  71609. })(BABYLON || (BABYLON = {}));
  71610. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  71611. "use strict";
  71612. var BABYLON;
  71613. (function (BABYLON) {
  71614. var TonemappingOperator;
  71615. (function (TonemappingOperator) {
  71616. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  71617. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  71618. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  71619. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  71620. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  71621. ;
  71622. var TonemapPostProcess = /** @class */ (function (_super) {
  71623. __extends(TonemapPostProcess, _super);
  71624. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  71625. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  71626. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71627. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  71628. _this._operator = _operator;
  71629. _this.exposureAdjustment = exposureAdjustment;
  71630. var defines = "#define ";
  71631. if (_this._operator === TonemappingOperator.Hable)
  71632. defines += "HABLE_TONEMAPPING";
  71633. else if (_this._operator === TonemappingOperator.Reinhard)
  71634. defines += "REINHARD_TONEMAPPING";
  71635. else if (_this._operator === TonemappingOperator.HejiDawson)
  71636. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  71637. else if (_this._operator === TonemappingOperator.Photographic)
  71638. defines += "PHOTOGRAPHIC_TONEMAPPING";
  71639. //sadly a second call to create the effect.
  71640. _this.updateEffect(defines);
  71641. _this.onApply = function (effect) {
  71642. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  71643. };
  71644. return _this;
  71645. }
  71646. return TonemapPostProcess;
  71647. }(BABYLON.PostProcess));
  71648. BABYLON.TonemapPostProcess = TonemapPostProcess;
  71649. })(BABYLON || (BABYLON = {}));
  71650. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  71651. "use strict";
  71652. var BABYLON;
  71653. (function (BABYLON) {
  71654. var DisplayPassPostProcess = /** @class */ (function (_super) {
  71655. __extends(DisplayPassPostProcess, _super);
  71656. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  71657. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  71658. }
  71659. return DisplayPassPostProcess;
  71660. }(BABYLON.PostProcess));
  71661. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  71662. })(BABYLON || (BABYLON = {}));
  71663. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  71664. "use strict";
  71665. var BABYLON;
  71666. (function (BABYLON) {
  71667. var HighlightsPostProcess = /** @class */ (function (_super) {
  71668. __extends(HighlightsPostProcess, _super);
  71669. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  71670. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71671. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  71672. }
  71673. return HighlightsPostProcess;
  71674. }(BABYLON.PostProcess));
  71675. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  71676. })(BABYLON || (BABYLON = {}));
  71677. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  71678. "use strict";
  71679. var BABYLON;
  71680. (function (BABYLON) {
  71681. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  71682. __extends(ImageProcessingPostProcess, _super);
  71683. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  71684. if (camera === void 0) { camera = null; }
  71685. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71686. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  71687. _this._fromLinearSpace = true;
  71688. /**
  71689. * Defines cache preventing GC.
  71690. */
  71691. _this._defines = {
  71692. IMAGEPROCESSING: false,
  71693. VIGNETTE: false,
  71694. VIGNETTEBLENDMODEMULTIPLY: false,
  71695. VIGNETTEBLENDMODEOPAQUE: false,
  71696. TONEMAPPING: false,
  71697. CONTRAST: false,
  71698. COLORCURVES: false,
  71699. COLORGRADING: false,
  71700. COLORGRADING3D: false,
  71701. FROMLINEARSPACE: false,
  71702. SAMPLER3DGREENDEPTH: false,
  71703. SAMPLER3DBGRMAP: false,
  71704. IMAGEPROCESSINGPOSTPROCESS: false,
  71705. EXPOSURE: false,
  71706. GRAIN: false,
  71707. };
  71708. // Setup the configuration as forced by the constructor. This would then not force the
  71709. // scene materials output in linear space and let untouched the default forward pass.
  71710. if (imageProcessingConfiguration) {
  71711. imageProcessingConfiguration.applyByPostProcess = true;
  71712. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  71713. // This will cause the shader to be compiled
  71714. _this.fromLinearSpace = false;
  71715. }
  71716. else {
  71717. _this._attachImageProcessingConfiguration(null, true);
  71718. _this.imageProcessingConfiguration.applyByPostProcess = true;
  71719. }
  71720. _this.onApply = function (effect) {
  71721. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  71722. };
  71723. return _this;
  71724. }
  71725. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  71726. /**
  71727. * Gets the image processing configuration used either in this material.
  71728. */
  71729. get: function () {
  71730. return this._imageProcessingConfiguration;
  71731. },
  71732. /**
  71733. * Sets the Default image processing configuration used either in the this material.
  71734. *
  71735. * If sets to null, the scene one is in use.
  71736. */
  71737. set: function (value) {
  71738. this._attachImageProcessingConfiguration(value);
  71739. },
  71740. enumerable: true,
  71741. configurable: true
  71742. });
  71743. /**
  71744. * Attaches a new image processing configuration to the PBR Material.
  71745. * @param configuration
  71746. */
  71747. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  71748. var _this = this;
  71749. if (doNotBuild === void 0) { doNotBuild = false; }
  71750. if (configuration === this._imageProcessingConfiguration) {
  71751. return;
  71752. }
  71753. // Detaches observer.
  71754. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  71755. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  71756. }
  71757. // Pick the scene configuration if needed.
  71758. if (!configuration) {
  71759. var scene = null;
  71760. var engine = this.getEngine();
  71761. var camera = this.getCamera();
  71762. if (camera) {
  71763. scene = camera.getScene();
  71764. }
  71765. else if (engine && engine.scenes) {
  71766. var scenes = engine.scenes;
  71767. scene = scenes[scenes.length - 1];
  71768. }
  71769. else {
  71770. scene = BABYLON.Engine.LastCreatedScene;
  71771. }
  71772. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  71773. }
  71774. else {
  71775. this._imageProcessingConfiguration = configuration;
  71776. }
  71777. // Attaches observer.
  71778. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  71779. _this._updateParameters();
  71780. });
  71781. // Ensure the effect will be rebuilt.
  71782. if (!doNotBuild) {
  71783. this._updateParameters();
  71784. }
  71785. };
  71786. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  71787. /**
  71788. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  71789. */
  71790. get: function () {
  71791. return this.imageProcessingConfiguration.colorCurves;
  71792. },
  71793. /**
  71794. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  71795. */
  71796. set: function (value) {
  71797. this.imageProcessingConfiguration.colorCurves = value;
  71798. },
  71799. enumerable: true,
  71800. configurable: true
  71801. });
  71802. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  71803. /**
  71804. * Gets wether the color curves effect is enabled.
  71805. */
  71806. get: function () {
  71807. return this.imageProcessingConfiguration.colorCurvesEnabled;
  71808. },
  71809. /**
  71810. * Sets wether the color curves effect is enabled.
  71811. */
  71812. set: function (value) {
  71813. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  71814. },
  71815. enumerable: true,
  71816. configurable: true
  71817. });
  71818. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  71819. /**
  71820. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  71821. */
  71822. get: function () {
  71823. return this.imageProcessingConfiguration.colorGradingTexture;
  71824. },
  71825. /**
  71826. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  71827. */
  71828. set: function (value) {
  71829. this.imageProcessingConfiguration.colorGradingTexture = value;
  71830. },
  71831. enumerable: true,
  71832. configurable: true
  71833. });
  71834. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  71835. /**
  71836. * Gets wether the color grading effect is enabled.
  71837. */
  71838. get: function () {
  71839. return this.imageProcessingConfiguration.colorGradingEnabled;
  71840. },
  71841. /**
  71842. * Gets wether the color grading effect is enabled.
  71843. */
  71844. set: function (value) {
  71845. this.imageProcessingConfiguration.colorGradingEnabled = value;
  71846. },
  71847. enumerable: true,
  71848. configurable: true
  71849. });
  71850. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  71851. /**
  71852. * Gets exposure used in the effect.
  71853. */
  71854. get: function () {
  71855. return this.imageProcessingConfiguration.exposure;
  71856. },
  71857. /**
  71858. * Sets exposure used in the effect.
  71859. */
  71860. set: function (value) {
  71861. this.imageProcessingConfiguration.exposure = value;
  71862. },
  71863. enumerable: true,
  71864. configurable: true
  71865. });
  71866. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  71867. /**
  71868. * Gets wether tonemapping is enabled or not.
  71869. */
  71870. get: function () {
  71871. return this._imageProcessingConfiguration.toneMappingEnabled;
  71872. },
  71873. /**
  71874. * Sets wether tonemapping is enabled or not
  71875. */
  71876. set: function (value) {
  71877. this._imageProcessingConfiguration.toneMappingEnabled = value;
  71878. },
  71879. enumerable: true,
  71880. configurable: true
  71881. });
  71882. ;
  71883. ;
  71884. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  71885. /**
  71886. * Gets contrast used in the effect.
  71887. */
  71888. get: function () {
  71889. return this.imageProcessingConfiguration.contrast;
  71890. },
  71891. /**
  71892. * Sets contrast used in the effect.
  71893. */
  71894. set: function (value) {
  71895. this.imageProcessingConfiguration.contrast = value;
  71896. },
  71897. enumerable: true,
  71898. configurable: true
  71899. });
  71900. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  71901. /**
  71902. * Gets Vignette stretch size.
  71903. */
  71904. get: function () {
  71905. return this.imageProcessingConfiguration.vignetteStretch;
  71906. },
  71907. /**
  71908. * Sets Vignette stretch size.
  71909. */
  71910. set: function (value) {
  71911. this.imageProcessingConfiguration.vignetteStretch = value;
  71912. },
  71913. enumerable: true,
  71914. configurable: true
  71915. });
  71916. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  71917. /**
  71918. * Gets Vignette centre X Offset.
  71919. */
  71920. get: function () {
  71921. return this.imageProcessingConfiguration.vignetteCentreX;
  71922. },
  71923. /**
  71924. * Sets Vignette centre X Offset.
  71925. */
  71926. set: function (value) {
  71927. this.imageProcessingConfiguration.vignetteCentreX = value;
  71928. },
  71929. enumerable: true,
  71930. configurable: true
  71931. });
  71932. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  71933. /**
  71934. * Gets Vignette centre Y Offset.
  71935. */
  71936. get: function () {
  71937. return this.imageProcessingConfiguration.vignetteCentreY;
  71938. },
  71939. /**
  71940. * Sets Vignette centre Y Offset.
  71941. */
  71942. set: function (value) {
  71943. this.imageProcessingConfiguration.vignetteCentreY = value;
  71944. },
  71945. enumerable: true,
  71946. configurable: true
  71947. });
  71948. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  71949. /**
  71950. * Gets Vignette weight or intensity of the vignette effect.
  71951. */
  71952. get: function () {
  71953. return this.imageProcessingConfiguration.vignetteWeight;
  71954. },
  71955. /**
  71956. * Sets Vignette weight or intensity of the vignette effect.
  71957. */
  71958. set: function (value) {
  71959. this.imageProcessingConfiguration.vignetteWeight = value;
  71960. },
  71961. enumerable: true,
  71962. configurable: true
  71963. });
  71964. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  71965. /**
  71966. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  71967. * if vignetteEnabled is set to true.
  71968. */
  71969. get: function () {
  71970. return this.imageProcessingConfiguration.vignetteColor;
  71971. },
  71972. /**
  71973. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  71974. * if vignetteEnabled is set to true.
  71975. */
  71976. set: function (value) {
  71977. this.imageProcessingConfiguration.vignetteColor = value;
  71978. },
  71979. enumerable: true,
  71980. configurable: true
  71981. });
  71982. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  71983. /**
  71984. * Gets Camera field of view used by the Vignette effect.
  71985. */
  71986. get: function () {
  71987. return this.imageProcessingConfiguration.vignetteCameraFov;
  71988. },
  71989. /**
  71990. * Sets Camera field of view used by the Vignette effect.
  71991. */
  71992. set: function (value) {
  71993. this.imageProcessingConfiguration.vignetteCameraFov = value;
  71994. },
  71995. enumerable: true,
  71996. configurable: true
  71997. });
  71998. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  71999. /**
  72000. * Gets the vignette blend mode allowing different kind of effect.
  72001. */
  72002. get: function () {
  72003. return this.imageProcessingConfiguration.vignetteBlendMode;
  72004. },
  72005. /**
  72006. * Sets the vignette blend mode allowing different kind of effect.
  72007. */
  72008. set: function (value) {
  72009. this.imageProcessingConfiguration.vignetteBlendMode = value;
  72010. },
  72011. enumerable: true,
  72012. configurable: true
  72013. });
  72014. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  72015. /**
  72016. * Gets wether the vignette effect is enabled.
  72017. */
  72018. get: function () {
  72019. return this.imageProcessingConfiguration.vignetteEnabled;
  72020. },
  72021. /**
  72022. * Sets wether the vignette effect is enabled.
  72023. */
  72024. set: function (value) {
  72025. this.imageProcessingConfiguration.vignetteEnabled = value;
  72026. },
  72027. enumerable: true,
  72028. configurable: true
  72029. });
  72030. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainEnabled", {
  72031. /**
  72032. * Gets wether the grain effect is enabled.
  72033. */
  72034. get: function () {
  72035. return this.imageProcessingConfiguration.grainEnabled;
  72036. },
  72037. /**
  72038. * Sets wether the grain effect is enabled.
  72039. */
  72040. set: function (value) {
  72041. this.imageProcessingConfiguration.grainEnabled = value;
  72042. },
  72043. enumerable: true,
  72044. configurable: true
  72045. });
  72046. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainIntensity", {
  72047. /**
  72048. * Gets the grain effect's intensity.
  72049. */
  72050. get: function () {
  72051. return this.imageProcessingConfiguration.grainIntensity;
  72052. },
  72053. /**
  72054. * Sets the grain effect's intensity.
  72055. */
  72056. set: function (value) {
  72057. this.imageProcessingConfiguration.grainIntensity = value;
  72058. },
  72059. enumerable: true,
  72060. configurable: true
  72061. });
  72062. Object.defineProperty(ImageProcessingPostProcess.prototype, "grainAnimated", {
  72063. /**
  72064. * Gets wether the grain effect is animated.
  72065. */
  72066. get: function () {
  72067. return this.imageProcessingConfiguration.grainAnimated;
  72068. },
  72069. /**
  72070. * Sets wether the grain effect is animated.
  72071. */
  72072. set: function (value) {
  72073. this.imageProcessingConfiguration.grainAnimated = value;
  72074. },
  72075. enumerable: true,
  72076. configurable: true
  72077. });
  72078. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  72079. /**
  72080. * Gets wether the input of the processing is in Gamma or Linear Space.
  72081. */
  72082. get: function () {
  72083. return this._fromLinearSpace;
  72084. },
  72085. /**
  72086. * Sets wether the input of the processing is in Gamma or Linear Space.
  72087. */
  72088. set: function (value) {
  72089. if (this._fromLinearSpace === value) {
  72090. return;
  72091. }
  72092. this._fromLinearSpace = value;
  72093. this._updateParameters();
  72094. },
  72095. enumerable: true,
  72096. configurable: true
  72097. });
  72098. ImageProcessingPostProcess.prototype.getClassName = function () {
  72099. return "ImageProcessingPostProcess";
  72100. };
  72101. ImageProcessingPostProcess.prototype._updateParameters = function () {
  72102. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  72103. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  72104. var defines = "";
  72105. for (var define in this._defines) {
  72106. if (this._defines[define]) {
  72107. defines += "#define " + define + ";\r\n";
  72108. }
  72109. }
  72110. var samplers = ["textureSampler"];
  72111. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  72112. var uniforms = ["scale"];
  72113. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  72114. this.updateEffect(defines, uniforms, samplers);
  72115. };
  72116. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  72117. _super.prototype.dispose.call(this, camera);
  72118. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  72119. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  72120. }
  72121. this.imageProcessingConfiguration.applyByPostProcess = false;
  72122. };
  72123. __decorate([
  72124. BABYLON.serialize()
  72125. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  72126. return ImageProcessingPostProcess;
  72127. }(BABYLON.PostProcess));
  72128. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  72129. })(BABYLON || (BABYLON = {}));
  72130. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  72131. "use strict";
  72132. var BABYLON;
  72133. (function (BABYLON) {
  72134. var Bone = /** @class */ (function (_super) {
  72135. __extends(Bone, _super);
  72136. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  72137. if (parentBone === void 0) { parentBone = null; }
  72138. if (localMatrix === void 0) { localMatrix = null; }
  72139. if (restPose === void 0) { restPose = null; }
  72140. if (baseMatrix === void 0) { baseMatrix = null; }
  72141. if (index === void 0) { index = null; }
  72142. var _this = _super.call(this, name, skeleton.getScene()) || this;
  72143. _this.name = name;
  72144. _this.children = new Array();
  72145. _this.animations = new Array();
  72146. // Set this value to map this bone to a different index in the transform matrices.
  72147. // Set this value to -1 to exclude the bone from the transform matrices.
  72148. _this._index = null;
  72149. _this._worldTransform = new BABYLON.Matrix();
  72150. _this._absoluteTransform = new BABYLON.Matrix();
  72151. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  72152. _this._scaleMatrix = BABYLON.Matrix.Identity();
  72153. _this._scaleVector = BABYLON.Vector3.One();
  72154. _this._negateScaleChildren = BABYLON.Vector3.One();
  72155. _this._scalingDeterminant = 1;
  72156. _this._skeleton = skeleton;
  72157. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  72158. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  72159. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  72160. _this._index = index;
  72161. skeleton.bones.push(_this);
  72162. _this.setParent(parentBone, false);
  72163. _this._updateDifferenceMatrix();
  72164. return _this;
  72165. }
  72166. Object.defineProperty(Bone.prototype, "_matrix", {
  72167. get: function () {
  72168. return this._localMatrix;
  72169. },
  72170. set: function (val) {
  72171. if (this._localMatrix) {
  72172. this._localMatrix.copyFrom(val);
  72173. }
  72174. else {
  72175. this._localMatrix = val;
  72176. }
  72177. },
  72178. enumerable: true,
  72179. configurable: true
  72180. });
  72181. // Members
  72182. Bone.prototype.getSkeleton = function () {
  72183. return this._skeleton;
  72184. };
  72185. Bone.prototype.getParent = function () {
  72186. return this._parent;
  72187. };
  72188. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  72189. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  72190. if (this._parent === parent) {
  72191. return;
  72192. }
  72193. if (this._parent) {
  72194. var index = this._parent.children.indexOf(this);
  72195. if (index !== -1) {
  72196. this._parent.children.splice(index, 1);
  72197. }
  72198. }
  72199. this._parent = parent;
  72200. if (this._parent) {
  72201. this._parent.children.push(this);
  72202. }
  72203. if (updateDifferenceMatrix) {
  72204. this._updateDifferenceMatrix();
  72205. }
  72206. };
  72207. Bone.prototype.getLocalMatrix = function () {
  72208. return this._localMatrix;
  72209. };
  72210. Bone.prototype.getBaseMatrix = function () {
  72211. return this._baseMatrix;
  72212. };
  72213. Bone.prototype.getRestPose = function () {
  72214. return this._restPose;
  72215. };
  72216. Bone.prototype.returnToRest = function () {
  72217. this.updateMatrix(this._restPose.clone());
  72218. };
  72219. Bone.prototype.getWorldMatrix = function () {
  72220. return this._worldTransform;
  72221. };
  72222. Bone.prototype.getInvertedAbsoluteTransform = function () {
  72223. return this._invertedAbsoluteTransform;
  72224. };
  72225. Bone.prototype.getAbsoluteTransform = function () {
  72226. return this._absoluteTransform;
  72227. };
  72228. Object.defineProperty(Bone.prototype, "position", {
  72229. // Properties (matches AbstractMesh properties)
  72230. get: function () {
  72231. return this.getPosition();
  72232. },
  72233. set: function (newPosition) {
  72234. this.setPosition(newPosition);
  72235. },
  72236. enumerable: true,
  72237. configurable: true
  72238. });
  72239. Object.defineProperty(Bone.prototype, "rotation", {
  72240. get: function () {
  72241. return this.getRotation();
  72242. },
  72243. set: function (newRotation) {
  72244. this.setRotation(newRotation);
  72245. },
  72246. enumerable: true,
  72247. configurable: true
  72248. });
  72249. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  72250. get: function () {
  72251. return this.getRotationQuaternion();
  72252. },
  72253. set: function (newRotation) {
  72254. this.setRotationQuaternion(newRotation);
  72255. },
  72256. enumerable: true,
  72257. configurable: true
  72258. });
  72259. Object.defineProperty(Bone.prototype, "scaling", {
  72260. get: function () {
  72261. return this.getScale();
  72262. },
  72263. set: function (newScaling) {
  72264. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  72265. },
  72266. enumerable: true,
  72267. configurable: true
  72268. });
  72269. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  72270. /**
  72271. * Gets the animation properties override
  72272. */
  72273. get: function () {
  72274. return this._skeleton.animationPropertiesOverride;
  72275. },
  72276. enumerable: true,
  72277. configurable: true
  72278. });
  72279. // Methods
  72280. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  72281. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  72282. this._baseMatrix = matrix.clone();
  72283. this._localMatrix = matrix.clone();
  72284. this._skeleton._markAsDirty();
  72285. if (updateDifferenceMatrix) {
  72286. this._updateDifferenceMatrix();
  72287. }
  72288. };
  72289. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  72290. if (!rootMatrix) {
  72291. rootMatrix = this._baseMatrix;
  72292. }
  72293. if (this._parent) {
  72294. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  72295. }
  72296. else {
  72297. this._absoluteTransform.copyFrom(rootMatrix);
  72298. }
  72299. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  72300. for (var index = 0; index < this.children.length; index++) {
  72301. this.children[index]._updateDifferenceMatrix();
  72302. }
  72303. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  72304. };
  72305. Bone.prototype.markAsDirty = function () {
  72306. this._currentRenderId++;
  72307. this._skeleton._markAsDirty();
  72308. };
  72309. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  72310. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  72311. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  72312. // all animation may be coming from a library skeleton, so may need to create animation
  72313. if (this.animations.length === 0) {
  72314. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  72315. this.animations[0].setKeys([]);
  72316. }
  72317. // get animation info / verify there is such a range from the source bone
  72318. var sourceRange = source.animations[0].getRange(rangeName);
  72319. if (!sourceRange) {
  72320. return false;
  72321. }
  72322. var from = sourceRange.from;
  72323. var to = sourceRange.to;
  72324. var sourceKeys = source.animations[0].getKeys();
  72325. // rescaling prep
  72326. var sourceBoneLength = source.length;
  72327. var sourceParent = source.getParent();
  72328. var parent = this.getParent();
  72329. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  72330. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  72331. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  72332. var destKeys = this.animations[0].getKeys();
  72333. // loop vars declaration
  72334. var orig;
  72335. var origTranslation;
  72336. var mat;
  72337. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  72338. orig = sourceKeys[key];
  72339. if (orig.frame >= from && orig.frame <= to) {
  72340. if (rescaleAsRequired) {
  72341. mat = orig.value.clone();
  72342. // scale based on parent ratio, when bone has parent
  72343. if (parentScalingReqd) {
  72344. origTranslation = mat.getTranslation();
  72345. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  72346. // scale based on skeleton dimension ratio when root bone, and value is passed
  72347. }
  72348. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  72349. origTranslation = mat.getTranslation();
  72350. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  72351. // use original when root bone, and no data for skelDimensionsRatio
  72352. }
  72353. else {
  72354. mat = orig.value;
  72355. }
  72356. }
  72357. else {
  72358. mat = orig.value;
  72359. }
  72360. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  72361. }
  72362. }
  72363. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  72364. return true;
  72365. };
  72366. /**
  72367. * Translate the bone in local or world space.
  72368. * @param vec The amount to translate the bone.
  72369. * @param space The space that the translation is in.
  72370. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72371. */
  72372. Bone.prototype.translate = function (vec, space, mesh) {
  72373. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72374. var lm = this.getLocalMatrix();
  72375. if (space == BABYLON.Space.LOCAL) {
  72376. lm.m[12] += vec.x;
  72377. lm.m[13] += vec.y;
  72378. lm.m[14] += vec.z;
  72379. }
  72380. else {
  72381. var wm = null;
  72382. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72383. if (mesh) {
  72384. wm = mesh.getWorldMatrix();
  72385. }
  72386. this._skeleton.computeAbsoluteTransforms();
  72387. var tmat = Bone._tmpMats[0];
  72388. var tvec = Bone._tmpVecs[0];
  72389. if (this._parent) {
  72390. if (mesh && wm) {
  72391. tmat.copyFrom(this._parent.getAbsoluteTransform());
  72392. tmat.multiplyToRef(wm, tmat);
  72393. }
  72394. else {
  72395. tmat.copyFrom(this._parent.getAbsoluteTransform());
  72396. }
  72397. }
  72398. tmat.m[12] = 0;
  72399. tmat.m[13] = 0;
  72400. tmat.m[14] = 0;
  72401. tmat.invert();
  72402. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  72403. lm.m[12] += tvec.x;
  72404. lm.m[13] += tvec.y;
  72405. lm.m[14] += tvec.z;
  72406. }
  72407. this.markAsDirty();
  72408. };
  72409. /**
  72410. * Set the postion of the bone in local or world space.
  72411. * @param position The position to set the bone.
  72412. * @param space The space that the position is in.
  72413. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72414. */
  72415. Bone.prototype.setPosition = function (position, space, mesh) {
  72416. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72417. var lm = this.getLocalMatrix();
  72418. if (space == BABYLON.Space.LOCAL) {
  72419. lm.m[12] = position.x;
  72420. lm.m[13] = position.y;
  72421. lm.m[14] = position.z;
  72422. }
  72423. else {
  72424. var wm = null;
  72425. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72426. if (mesh) {
  72427. wm = mesh.getWorldMatrix();
  72428. }
  72429. this._skeleton.computeAbsoluteTransforms();
  72430. var tmat = Bone._tmpMats[0];
  72431. var vec = Bone._tmpVecs[0];
  72432. if (this._parent) {
  72433. if (mesh && wm) {
  72434. tmat.copyFrom(this._parent.getAbsoluteTransform());
  72435. tmat.multiplyToRef(wm, tmat);
  72436. }
  72437. else {
  72438. tmat.copyFrom(this._parent.getAbsoluteTransform());
  72439. }
  72440. }
  72441. tmat.invert();
  72442. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  72443. lm.m[12] = vec.x;
  72444. lm.m[13] = vec.y;
  72445. lm.m[14] = vec.z;
  72446. }
  72447. this.markAsDirty();
  72448. };
  72449. /**
  72450. * Set the absolute postion of the bone (world space).
  72451. * @param position The position to set the bone.
  72452. * @param mesh The mesh that this bone is attached to.
  72453. */
  72454. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  72455. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  72456. };
  72457. /**
  72458. * Set the scale of the bone on the x, y and z axes.
  72459. * @param x The scale of the bone on the x axis.
  72460. * @param x The scale of the bone on the y axis.
  72461. * @param z The scale of the bone on the z axis.
  72462. * @param scaleChildren Set this to true if children of the bone should be scaled.
  72463. */
  72464. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  72465. if (scaleChildren === void 0) { scaleChildren = false; }
  72466. if (this.animations[0] && !this.animations[0].hasRunningRuntimeAnimations) {
  72467. if (!scaleChildren) {
  72468. this._negateScaleChildren.x = 1 / x;
  72469. this._negateScaleChildren.y = 1 / y;
  72470. this._negateScaleChildren.z = 1 / z;
  72471. }
  72472. this._syncScaleVector();
  72473. }
  72474. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  72475. };
  72476. /**
  72477. * Scale the bone on the x, y and z axes.
  72478. * @param x The amount to scale the bone on the x axis.
  72479. * @param x The amount to scale the bone on the y axis.
  72480. * @param z The amount to scale the bone on the z axis.
  72481. * @param scaleChildren Set this to true if children of the bone should be scaled.
  72482. */
  72483. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  72484. if (scaleChildren === void 0) { scaleChildren = false; }
  72485. var locMat = this.getLocalMatrix();
  72486. var origLocMat = Bone._tmpMats[0];
  72487. origLocMat.copyFrom(locMat);
  72488. var origLocMatInv = Bone._tmpMats[1];
  72489. origLocMatInv.copyFrom(origLocMat);
  72490. origLocMatInv.invert();
  72491. var scaleMat = Bone._tmpMats[2];
  72492. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  72493. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  72494. this._scaleVector.x *= x;
  72495. this._scaleVector.y *= y;
  72496. this._scaleVector.z *= z;
  72497. locMat.multiplyToRef(origLocMatInv, locMat);
  72498. locMat.multiplyToRef(scaleMat, locMat);
  72499. locMat.multiplyToRef(origLocMat, locMat);
  72500. var parent = this.getParent();
  72501. if (parent) {
  72502. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  72503. }
  72504. else {
  72505. this.getAbsoluteTransform().copyFrom(locMat);
  72506. }
  72507. var len = this.children.length;
  72508. scaleMat.invert();
  72509. for (var i = 0; i < len; i++) {
  72510. var child = this.children[i];
  72511. var cm = child.getLocalMatrix();
  72512. cm.multiplyToRef(scaleMat, cm);
  72513. var lm = child.getLocalMatrix();
  72514. lm.m[12] *= x;
  72515. lm.m[13] *= y;
  72516. lm.m[14] *= z;
  72517. }
  72518. this.computeAbsoluteTransforms();
  72519. if (scaleChildren) {
  72520. for (var i = 0; i < len; i++) {
  72521. this.children[i].scale(x, y, z, scaleChildren);
  72522. }
  72523. }
  72524. this.markAsDirty();
  72525. };
  72526. /**
  72527. * Set the yaw, pitch, and roll of the bone in local or world space.
  72528. * @param yaw The rotation of the bone on the y axis.
  72529. * @param pitch The rotation of the bone on the x axis.
  72530. * @param roll The rotation of the bone on the z axis.
  72531. * @param space The space that the axes of rotation are in.
  72532. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72533. */
  72534. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  72535. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72536. var rotMat = Bone._tmpMats[0];
  72537. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  72538. var rotMatInv = Bone._tmpMats[1];
  72539. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  72540. rotMatInv.multiplyToRef(rotMat, rotMat);
  72541. this._rotateWithMatrix(rotMat, space, mesh);
  72542. };
  72543. /**
  72544. * Rotate the bone on an axis in local or world space.
  72545. * @param axis The axis to rotate the bone on.
  72546. * @param amount The amount to rotate the bone.
  72547. * @param space The space that the axis is in.
  72548. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72549. */
  72550. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  72551. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72552. var rmat = Bone._tmpMats[0];
  72553. rmat.m[12] = 0;
  72554. rmat.m[13] = 0;
  72555. rmat.m[14] = 0;
  72556. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  72557. this._rotateWithMatrix(rmat, space, mesh);
  72558. };
  72559. /**
  72560. * Set the rotation of the bone to a particular axis angle in local or world space.
  72561. * @param axis The axis to rotate the bone on.
  72562. * @param angle The angle that the bone should be rotated to.
  72563. * @param space The space that the axis is in.
  72564. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72565. */
  72566. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  72567. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72568. var rotMat = Bone._tmpMats[0];
  72569. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  72570. var rotMatInv = Bone._tmpMats[1];
  72571. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  72572. rotMatInv.multiplyToRef(rotMat, rotMat);
  72573. this._rotateWithMatrix(rotMat, space, mesh);
  72574. };
  72575. /**
  72576. * Set the euler rotation of the bone in local of world space.
  72577. * @param rotation The euler rotation that the bone should be set to.
  72578. * @param space The space that the rotation is in.
  72579. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72580. */
  72581. Bone.prototype.setRotation = function (rotation, space, mesh) {
  72582. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72583. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  72584. };
  72585. /**
  72586. * Set the quaternion rotation of the bone in local of world space.
  72587. * @param quat The quaternion rotation that the bone should be set to.
  72588. * @param space The space that the rotation is in.
  72589. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72590. */
  72591. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  72592. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72593. var rotMatInv = Bone._tmpMats[0];
  72594. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  72595. var rotMat = Bone._tmpMats[1];
  72596. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  72597. rotMatInv.multiplyToRef(rotMat, rotMat);
  72598. this._rotateWithMatrix(rotMat, space, mesh);
  72599. };
  72600. /**
  72601. * Set the rotation matrix of the bone in local of world space.
  72602. * @param rotMat The rotation matrix that the bone should be set to.
  72603. * @param space The space that the rotation is in.
  72604. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72605. */
  72606. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  72607. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72608. var rotMatInv = Bone._tmpMats[0];
  72609. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  72610. var rotMat2 = Bone._tmpMats[1];
  72611. rotMat2.copyFrom(rotMat);
  72612. rotMatInv.multiplyToRef(rotMat, rotMat2);
  72613. this._rotateWithMatrix(rotMat2, space, mesh);
  72614. };
  72615. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  72616. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72617. var lmat = this.getLocalMatrix();
  72618. var lx = lmat.m[12];
  72619. var ly = lmat.m[13];
  72620. var lz = lmat.m[14];
  72621. var parent = this.getParent();
  72622. var parentScale = Bone._tmpMats[3];
  72623. var parentScaleInv = Bone._tmpMats[4];
  72624. if (parent) {
  72625. if (space == BABYLON.Space.WORLD) {
  72626. if (mesh) {
  72627. parentScale.copyFrom(mesh.getWorldMatrix());
  72628. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  72629. }
  72630. else {
  72631. parentScale.copyFrom(parent.getAbsoluteTransform());
  72632. }
  72633. }
  72634. else {
  72635. parentScale = parent._scaleMatrix;
  72636. }
  72637. parentScaleInv.copyFrom(parentScale);
  72638. parentScaleInv.invert();
  72639. lmat.multiplyToRef(parentScale, lmat);
  72640. lmat.multiplyToRef(rmat, lmat);
  72641. lmat.multiplyToRef(parentScaleInv, lmat);
  72642. }
  72643. else {
  72644. if (space == BABYLON.Space.WORLD && mesh) {
  72645. parentScale.copyFrom(mesh.getWorldMatrix());
  72646. parentScaleInv.copyFrom(parentScale);
  72647. parentScaleInv.invert();
  72648. lmat.multiplyToRef(parentScale, lmat);
  72649. lmat.multiplyToRef(rmat, lmat);
  72650. lmat.multiplyToRef(parentScaleInv, lmat);
  72651. }
  72652. else {
  72653. lmat.multiplyToRef(rmat, lmat);
  72654. }
  72655. }
  72656. lmat.m[12] = lx;
  72657. lmat.m[13] = ly;
  72658. lmat.m[14] = lz;
  72659. this.computeAbsoluteTransforms();
  72660. this.markAsDirty();
  72661. };
  72662. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  72663. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72664. if (space == BABYLON.Space.WORLD) {
  72665. var scaleMatrix = Bone._tmpMats[2];
  72666. scaleMatrix.copyFrom(this._scaleMatrix);
  72667. rotMatInv.copyFrom(this.getAbsoluteTransform());
  72668. if (mesh) {
  72669. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  72670. var meshScale = Bone._tmpMats[3];
  72671. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  72672. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  72673. }
  72674. rotMatInv.invert();
  72675. scaleMatrix.m[0] *= this._scalingDeterminant;
  72676. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  72677. }
  72678. else {
  72679. rotMatInv.copyFrom(this.getLocalMatrix());
  72680. rotMatInv.invert();
  72681. var scaleMatrix = Bone._tmpMats[2];
  72682. scaleMatrix.copyFrom(this._scaleMatrix);
  72683. if (this._parent) {
  72684. var pscaleMatrix = Bone._tmpMats[3];
  72685. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  72686. pscaleMatrix.invert();
  72687. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  72688. }
  72689. else {
  72690. scaleMatrix.m[0] *= this._scalingDeterminant;
  72691. }
  72692. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  72693. }
  72694. };
  72695. /**
  72696. * Get the scale of the bone
  72697. * @returns the scale of the bone
  72698. */
  72699. Bone.prototype.getScale = function () {
  72700. return this._scaleVector.clone();
  72701. };
  72702. /**
  72703. * Copy the scale of the bone to a vector3.
  72704. * @param result The vector3 to copy the scale to
  72705. */
  72706. Bone.prototype.getScaleToRef = function (result) {
  72707. result.copyFrom(this._scaleVector);
  72708. };
  72709. /**
  72710. * Get the position of the bone in local or world space.
  72711. * @param space The space that the returned position is in.
  72712. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72713. * @returns The position of the bone
  72714. */
  72715. Bone.prototype.getPosition = function (space, mesh) {
  72716. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72717. if (mesh === void 0) { mesh = null; }
  72718. var pos = BABYLON.Vector3.Zero();
  72719. this.getPositionToRef(space, mesh, pos);
  72720. return pos;
  72721. };
  72722. /**
  72723. * Copy the position of the bone to a vector3 in local or world space.
  72724. * @param space The space that the returned position is in.
  72725. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72726. * @param result The vector3 to copy the position to.
  72727. */
  72728. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  72729. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72730. if (space == BABYLON.Space.LOCAL) {
  72731. var lm = this.getLocalMatrix();
  72732. result.x = lm.m[12];
  72733. result.y = lm.m[13];
  72734. result.z = lm.m[14];
  72735. }
  72736. else {
  72737. var wm = null;
  72738. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72739. if (mesh) {
  72740. wm = mesh.getWorldMatrix();
  72741. }
  72742. this._skeleton.computeAbsoluteTransforms();
  72743. var tmat = Bone._tmpMats[0];
  72744. if (mesh && wm) {
  72745. tmat.copyFrom(this.getAbsoluteTransform());
  72746. tmat.multiplyToRef(wm, tmat);
  72747. }
  72748. else {
  72749. tmat = this.getAbsoluteTransform();
  72750. }
  72751. result.x = tmat.m[12];
  72752. result.y = tmat.m[13];
  72753. result.z = tmat.m[14];
  72754. }
  72755. };
  72756. /**
  72757. * Get the absolute position of the bone (world space).
  72758. * @param mesh The mesh that this bone is attached to.
  72759. * @returns The absolute position of the bone
  72760. */
  72761. Bone.prototype.getAbsolutePosition = function (mesh) {
  72762. if (mesh === void 0) { mesh = null; }
  72763. var pos = BABYLON.Vector3.Zero();
  72764. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  72765. return pos;
  72766. };
  72767. /**
  72768. * Copy the absolute position of the bone (world space) to the result param.
  72769. * @param mesh The mesh that this bone is attached to.
  72770. * @param result The vector3 to copy the absolute position to.
  72771. */
  72772. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  72773. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  72774. };
  72775. /**
  72776. * Compute the absolute transforms of this bone and its children.
  72777. */
  72778. Bone.prototype.computeAbsoluteTransforms = function () {
  72779. if (this._parent) {
  72780. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  72781. }
  72782. else {
  72783. this._absoluteTransform.copyFrom(this._localMatrix);
  72784. var poseMatrix = this._skeleton.getPoseMatrix();
  72785. if (poseMatrix) {
  72786. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  72787. }
  72788. }
  72789. var children = this.children;
  72790. var len = children.length;
  72791. for (var i = 0; i < len; i++) {
  72792. children[i].computeAbsoluteTransforms();
  72793. }
  72794. };
  72795. Bone.prototype._syncScaleVector = function () {
  72796. var lm = this.getLocalMatrix();
  72797. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  72798. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  72799. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  72800. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  72801. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  72802. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  72803. this._scaleVector.x = xs * Math.sqrt(xsq);
  72804. this._scaleVector.y = ys * Math.sqrt(ysq);
  72805. this._scaleVector.z = zs * Math.sqrt(zsq);
  72806. if (this._parent) {
  72807. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  72808. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  72809. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  72810. }
  72811. BABYLON.Matrix.FromValuesToRef(this._scaleVector.x, 0, 0, 0, 0, this._scaleVector.y, 0, 0, 0, 0, this._scaleVector.z, 0, 0, 0, 0, 1, this._scaleMatrix);
  72812. };
  72813. /**
  72814. * Get the world direction from an axis that is in the local space of the bone.
  72815. * @param localAxis The local direction that is used to compute the world direction.
  72816. * @param mesh The mesh that this bone is attached to.
  72817. * @returns The world direction
  72818. */
  72819. Bone.prototype.getDirection = function (localAxis, mesh) {
  72820. if (mesh === void 0) { mesh = null; }
  72821. var result = BABYLON.Vector3.Zero();
  72822. this.getDirectionToRef(localAxis, mesh, result);
  72823. return result;
  72824. };
  72825. /**
  72826. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  72827. * @param localAxis The local direction that is used to compute the world direction.
  72828. * @param mesh The mesh that this bone is attached to.
  72829. * @param result The vector3 that the world direction will be copied to.
  72830. */
  72831. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  72832. if (mesh === void 0) { mesh = null; }
  72833. var wm = null;
  72834. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72835. if (mesh) {
  72836. wm = mesh.getWorldMatrix();
  72837. }
  72838. this._skeleton.computeAbsoluteTransforms();
  72839. var mat = Bone._tmpMats[0];
  72840. mat.copyFrom(this.getAbsoluteTransform());
  72841. if (mesh && wm) {
  72842. mat.multiplyToRef(wm, mat);
  72843. }
  72844. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  72845. result.normalize();
  72846. };
  72847. /**
  72848. * Get the euler rotation of the bone in local or world space.
  72849. * @param space The space that the rotation should be in.
  72850. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72851. * @returns The euler rotation
  72852. */
  72853. Bone.prototype.getRotation = function (space, mesh) {
  72854. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72855. if (mesh === void 0) { mesh = null; }
  72856. var result = BABYLON.Vector3.Zero();
  72857. this.getRotationToRef(space, mesh, result);
  72858. return result;
  72859. };
  72860. /**
  72861. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  72862. * @param space The space that the rotation should be in.
  72863. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72864. * @param result The vector3 that the rotation should be copied to.
  72865. */
  72866. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  72867. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72868. if (mesh === void 0) { mesh = null; }
  72869. var quat = Bone._tmpQuat;
  72870. this.getRotationQuaternionToRef(space, mesh, quat);
  72871. quat.toEulerAnglesToRef(result);
  72872. };
  72873. /**
  72874. * Get the quaternion rotation of the bone in either local or world space.
  72875. * @param space The space that the rotation should be in.
  72876. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72877. * @returns The quaternion rotation
  72878. */
  72879. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  72880. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72881. if (mesh === void 0) { mesh = null; }
  72882. var result = BABYLON.Quaternion.Identity();
  72883. this.getRotationQuaternionToRef(space, mesh, result);
  72884. return result;
  72885. };
  72886. /**
  72887. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  72888. * @param space The space that the rotation should be in.
  72889. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72890. * @param result The quaternion that the rotation should be copied to.
  72891. */
  72892. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  72893. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72894. if (mesh === void 0) { mesh = null; }
  72895. if (space == BABYLON.Space.LOCAL) {
  72896. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  72897. }
  72898. else {
  72899. var mat = Bone._tmpMats[0];
  72900. var amat = this.getAbsoluteTransform();
  72901. if (mesh) {
  72902. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  72903. }
  72904. else {
  72905. mat.copyFrom(amat);
  72906. }
  72907. mat.m[0] *= this._scalingDeterminant;
  72908. mat.m[1] *= this._scalingDeterminant;
  72909. mat.m[2] *= this._scalingDeterminant;
  72910. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  72911. }
  72912. };
  72913. /**
  72914. * Get the rotation matrix of the bone in local or world space.
  72915. * @param space The space that the rotation should be in.
  72916. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72917. * @returns The rotation matrix
  72918. */
  72919. Bone.prototype.getRotationMatrix = function (space, mesh) {
  72920. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72921. var result = BABYLON.Matrix.Identity();
  72922. this.getRotationMatrixToRef(space, mesh, result);
  72923. return result;
  72924. };
  72925. /**
  72926. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  72927. * @param space The space that the rotation should be in.
  72928. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  72929. * @param result The quaternion that the rotation should be copied to.
  72930. */
  72931. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  72932. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  72933. if (space == BABYLON.Space.LOCAL) {
  72934. this.getLocalMatrix().getRotationMatrixToRef(result);
  72935. }
  72936. else {
  72937. var mat = Bone._tmpMats[0];
  72938. var amat = this.getAbsoluteTransform();
  72939. if (mesh) {
  72940. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  72941. }
  72942. else {
  72943. mat.copyFrom(amat);
  72944. }
  72945. mat.m[0] *= this._scalingDeterminant;
  72946. mat.m[1] *= this._scalingDeterminant;
  72947. mat.m[2] *= this._scalingDeterminant;
  72948. mat.getRotationMatrixToRef(result);
  72949. }
  72950. };
  72951. /**
  72952. * Get the world position of a point that is in the local space of the bone.
  72953. * @param position The local position
  72954. * @param mesh The mesh that this bone is attached to.
  72955. * @returns The world position
  72956. */
  72957. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  72958. if (mesh === void 0) { mesh = null; }
  72959. var result = BABYLON.Vector3.Zero();
  72960. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  72961. return result;
  72962. };
  72963. /**
  72964. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  72965. * @param position The local position
  72966. * @param mesh The mesh that this bone is attached to.
  72967. * @param result The vector3 that the world position should be copied to.
  72968. */
  72969. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  72970. if (mesh === void 0) { mesh = null; }
  72971. var wm = null;
  72972. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  72973. if (mesh) {
  72974. wm = mesh.getWorldMatrix();
  72975. }
  72976. this._skeleton.computeAbsoluteTransforms();
  72977. var tmat = Bone._tmpMats[0];
  72978. if (mesh && wm) {
  72979. tmat.copyFrom(this.getAbsoluteTransform());
  72980. tmat.multiplyToRef(wm, tmat);
  72981. }
  72982. else {
  72983. tmat = this.getAbsoluteTransform();
  72984. }
  72985. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  72986. };
  72987. /**
  72988. * Get the local position of a point that is in world space.
  72989. * @param position The world position
  72990. * @param mesh The mesh that this bone is attached to.
  72991. * @returns The local position
  72992. */
  72993. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  72994. if (mesh === void 0) { mesh = null; }
  72995. var result = BABYLON.Vector3.Zero();
  72996. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  72997. return result;
  72998. };
  72999. /**
  73000. * Get the local position of a point that is in world space and copy it to the result param.
  73001. * @param position The world position
  73002. * @param mesh The mesh that this bone is attached to.
  73003. * @param result The vector3 that the local position should be copied to.
  73004. */
  73005. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  73006. if (mesh === void 0) { mesh = null; }
  73007. var wm = null;
  73008. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  73009. if (mesh) {
  73010. wm = mesh.getWorldMatrix();
  73011. }
  73012. this._skeleton.computeAbsoluteTransforms();
  73013. var tmat = Bone._tmpMats[0];
  73014. tmat.copyFrom(this.getAbsoluteTransform());
  73015. if (mesh && wm) {
  73016. tmat.multiplyToRef(wm, tmat);
  73017. }
  73018. tmat.invert();
  73019. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  73020. };
  73021. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73022. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  73023. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  73024. return Bone;
  73025. }(BABYLON.Node));
  73026. BABYLON.Bone = Bone;
  73027. })(BABYLON || (BABYLON = {}));
  73028. //# sourceMappingURL=babylon.bone.js.map
  73029. "use strict";
  73030. var BABYLON;
  73031. (function (BABYLON) {
  73032. var BoneIKController = /** @class */ (function () {
  73033. function BoneIKController(mesh, bone, options) {
  73034. this.targetPosition = BABYLON.Vector3.Zero();
  73035. this.poleTargetPosition = BABYLON.Vector3.Zero();
  73036. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  73037. this.poleAngle = 0;
  73038. this.slerpAmount = 1;
  73039. this._bone1Quat = BABYLON.Quaternion.Identity();
  73040. this._bone1Mat = BABYLON.Matrix.Identity();
  73041. this._bone2Ang = Math.PI;
  73042. this._maxAngle = Math.PI;
  73043. this._rightHandedSystem = false;
  73044. this._bendAxis = BABYLON.Vector3.Right();
  73045. this._slerping = false;
  73046. this._adjustRoll = 0;
  73047. this._bone2 = bone;
  73048. this._bone1 = bone.getParent();
  73049. if (!this._bone1) {
  73050. return;
  73051. }
  73052. this.mesh = mesh;
  73053. var bonePos = bone.getPosition();
  73054. if (bone.getAbsoluteTransform().determinant() > 0) {
  73055. this._rightHandedSystem = true;
  73056. this._bendAxis.x = 0;
  73057. this._bendAxis.y = 0;
  73058. this._bendAxis.z = -1;
  73059. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  73060. this._adjustRoll = Math.PI * .5;
  73061. this._bendAxis.z = 1;
  73062. }
  73063. }
  73064. if (this._bone1.length) {
  73065. var boneScale1 = this._bone1.getScale();
  73066. var boneScale2 = this._bone2.getScale();
  73067. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  73068. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  73069. }
  73070. else if (this._bone1.children[0]) {
  73071. mesh.computeWorldMatrix(true);
  73072. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  73073. var pos2 = this._bone2.getAbsolutePosition(mesh);
  73074. var pos3 = this._bone1.getAbsolutePosition(mesh);
  73075. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  73076. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  73077. }
  73078. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  73079. this.maxAngle = Math.PI;
  73080. if (options) {
  73081. if (options.targetMesh) {
  73082. this.targetMesh = options.targetMesh;
  73083. this.targetMesh.computeWorldMatrix(true);
  73084. }
  73085. if (options.poleTargetMesh) {
  73086. this.poleTargetMesh = options.poleTargetMesh;
  73087. this.poleTargetMesh.computeWorldMatrix(true);
  73088. }
  73089. else if (options.poleTargetBone) {
  73090. this.poleTargetBone = options.poleTargetBone;
  73091. }
  73092. else if (this._bone1.getParent()) {
  73093. this.poleTargetBone = this._bone1.getParent();
  73094. }
  73095. if (options.poleTargetLocalOffset) {
  73096. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  73097. }
  73098. if (options.poleAngle) {
  73099. this.poleAngle = options.poleAngle;
  73100. }
  73101. if (options.bendAxis) {
  73102. this._bendAxis.copyFrom(options.bendAxis);
  73103. }
  73104. if (options.maxAngle) {
  73105. this.maxAngle = options.maxAngle;
  73106. }
  73107. if (options.slerpAmount) {
  73108. this.slerpAmount = options.slerpAmount;
  73109. }
  73110. }
  73111. }
  73112. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  73113. get: function () {
  73114. return this._maxAngle;
  73115. },
  73116. set: function (value) {
  73117. this._setMaxAngle(value);
  73118. },
  73119. enumerable: true,
  73120. configurable: true
  73121. });
  73122. BoneIKController.prototype._setMaxAngle = function (ang) {
  73123. if (ang < 0) {
  73124. ang = 0;
  73125. }
  73126. if (ang > Math.PI || ang == undefined) {
  73127. ang = Math.PI;
  73128. }
  73129. this._maxAngle = ang;
  73130. var a = this._bone1Length;
  73131. var b = this._bone2Length;
  73132. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  73133. };
  73134. BoneIKController.prototype.update = function () {
  73135. var bone1 = this._bone1;
  73136. if (!bone1) {
  73137. return;
  73138. }
  73139. var target = this.targetPosition;
  73140. var poleTarget = this.poleTargetPosition;
  73141. var mat1 = BoneIKController._tmpMats[0];
  73142. var mat2 = BoneIKController._tmpMats[1];
  73143. if (this.targetMesh) {
  73144. target.copyFrom(this.targetMesh.getAbsolutePosition());
  73145. }
  73146. if (this.poleTargetBone) {
  73147. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  73148. }
  73149. else if (this.poleTargetMesh) {
  73150. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  73151. }
  73152. var bonePos = BoneIKController._tmpVecs[0];
  73153. var zaxis = BoneIKController._tmpVecs[1];
  73154. var xaxis = BoneIKController._tmpVecs[2];
  73155. var yaxis = BoneIKController._tmpVecs[3];
  73156. var upAxis = BoneIKController._tmpVecs[4];
  73157. var _tmpQuat = BoneIKController._tmpQuat;
  73158. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  73159. poleTarget.subtractToRef(bonePos, upAxis);
  73160. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  73161. upAxis.y = 1;
  73162. }
  73163. else {
  73164. upAxis.normalize();
  73165. }
  73166. target.subtractToRef(bonePos, yaxis);
  73167. yaxis.normalize();
  73168. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  73169. zaxis.normalize();
  73170. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  73171. xaxis.normalize();
  73172. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  73173. var a = this._bone1Length;
  73174. var b = this._bone2Length;
  73175. var c = BABYLON.Vector3.Distance(bonePos, target);
  73176. if (this._maxReach > 0) {
  73177. c = Math.min(this._maxReach, c);
  73178. }
  73179. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  73180. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  73181. if (acosa > 1) {
  73182. acosa = 1;
  73183. }
  73184. if (acosb > 1) {
  73185. acosb = 1;
  73186. }
  73187. if (acosa < -1) {
  73188. acosa = -1;
  73189. }
  73190. if (acosb < -1) {
  73191. acosb = -1;
  73192. }
  73193. var angA = Math.acos(acosa);
  73194. var angB = Math.acos(acosb);
  73195. var angC = -angA - angB;
  73196. if (this._rightHandedSystem) {
  73197. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  73198. mat2.multiplyToRef(mat1, mat1);
  73199. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  73200. mat2.multiplyToRef(mat1, mat1);
  73201. }
  73202. else {
  73203. var _tmpVec = BoneIKController._tmpVecs[5];
  73204. _tmpVec.copyFrom(this._bendAxis);
  73205. _tmpVec.x *= -1;
  73206. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  73207. mat2.multiplyToRef(mat1, mat1);
  73208. }
  73209. if (this.poleAngle) {
  73210. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  73211. mat1.multiplyToRef(mat2, mat1);
  73212. }
  73213. if (this._bone1) {
  73214. if (this.slerpAmount < 1) {
  73215. if (!this._slerping) {
  73216. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  73217. }
  73218. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  73219. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  73220. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  73221. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  73222. this._slerping = true;
  73223. }
  73224. else {
  73225. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  73226. this._bone1Mat.copyFrom(mat1);
  73227. this._slerping = false;
  73228. }
  73229. }
  73230. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  73231. this._bone2Ang = angC;
  73232. };
  73233. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  73234. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  73235. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  73236. return BoneIKController;
  73237. }());
  73238. BABYLON.BoneIKController = BoneIKController;
  73239. })(BABYLON || (BABYLON = {}));
  73240. //# sourceMappingURL=babylon.boneIKController.js.map
  73241. "use strict";
  73242. var BABYLON;
  73243. (function (BABYLON) {
  73244. var BoneLookController = /** @class */ (function () {
  73245. /**
  73246. * Create a BoneLookController
  73247. * @param mesh the mesh that the bone belongs to
  73248. * @param bone the bone that will be looking to the target
  73249. * @param target the target Vector3 to look at
  73250. * @param settings optional settings:
  73251. * - maxYaw: the maximum angle the bone will yaw to
  73252. * - minYaw: the minimum angle the bone will yaw to
  73253. * - maxPitch: the maximum angle the bone will pitch to
  73254. * - minPitch: the minimum angle the bone will yaw to
  73255. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  73256. * - upAxis: the up axis of the coordinate system
  73257. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  73258. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  73259. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  73260. * - adjustYaw: used to make an adjustment to the yaw of the bone
  73261. * - adjustPitch: used to make an adjustment to the pitch of the bone
  73262. * - adjustRoll: used to make an adjustment to the roll of the bone
  73263. **/
  73264. function BoneLookController(mesh, bone, target, options) {
  73265. /**
  73266. * The up axis of the coordinate system that is used when the bone is rotated.
  73267. */
  73268. this.upAxis = BABYLON.Vector3.Up();
  73269. /**
  73270. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  73271. */
  73272. this.upAxisSpace = BABYLON.Space.LOCAL;
  73273. /**
  73274. * Used to make an adjustment to the yaw of the bone.
  73275. */
  73276. this.adjustYaw = 0;
  73277. /**
  73278. * Used to make an adjustment to the pitch of the bone.
  73279. */
  73280. this.adjustPitch = 0;
  73281. /**
  73282. * Used to make an adjustment to the roll of the bone.
  73283. */
  73284. this.adjustRoll = 0;
  73285. /**
  73286. * 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).
  73287. */
  73288. this.slerpAmount = 1;
  73289. this._boneQuat = BABYLON.Quaternion.Identity();
  73290. this._slerping = false;
  73291. this._firstFrameSkipped = false;
  73292. this._fowardAxis = BABYLON.Vector3.Forward();
  73293. this.mesh = mesh;
  73294. this.bone = bone;
  73295. this.target = target;
  73296. if (options) {
  73297. if (options.adjustYaw) {
  73298. this.adjustYaw = options.adjustYaw;
  73299. }
  73300. if (options.adjustPitch) {
  73301. this.adjustPitch = options.adjustPitch;
  73302. }
  73303. if (options.adjustRoll) {
  73304. this.adjustRoll = options.adjustRoll;
  73305. }
  73306. if (options.maxYaw != null) {
  73307. this.maxYaw = options.maxYaw;
  73308. }
  73309. else {
  73310. this.maxYaw = Math.PI;
  73311. }
  73312. if (options.minYaw != null) {
  73313. this.minYaw = options.minYaw;
  73314. }
  73315. else {
  73316. this.minYaw = -Math.PI;
  73317. }
  73318. if (options.maxPitch != null) {
  73319. this.maxPitch = options.maxPitch;
  73320. }
  73321. else {
  73322. this.maxPitch = Math.PI;
  73323. }
  73324. if (options.minPitch != null) {
  73325. this.minPitch = options.minPitch;
  73326. }
  73327. else {
  73328. this.minPitch = -Math.PI;
  73329. }
  73330. if (options.slerpAmount != null) {
  73331. this.slerpAmount = options.slerpAmount;
  73332. }
  73333. if (options.upAxis != null) {
  73334. this.upAxis = options.upAxis;
  73335. }
  73336. if (options.upAxisSpace != null) {
  73337. this.upAxisSpace = options.upAxisSpace;
  73338. }
  73339. if (options.yawAxis != null || options.pitchAxis != null) {
  73340. var newYawAxis = BABYLON.Axis.Y;
  73341. var newPitchAxis = BABYLON.Axis.X;
  73342. if (options.yawAxis != null) {
  73343. newYawAxis = options.yawAxis.clone();
  73344. newYawAxis.normalize();
  73345. }
  73346. if (options.pitchAxis != null) {
  73347. newPitchAxis = options.pitchAxis.clone();
  73348. newPitchAxis.normalize();
  73349. }
  73350. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  73351. this._transformYawPitch = BABYLON.Matrix.Identity();
  73352. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  73353. this._transformYawPitchInv = this._transformYawPitch.clone();
  73354. this._transformYawPitch.invert();
  73355. }
  73356. }
  73357. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  73358. this.upAxisSpace = BABYLON.Space.LOCAL;
  73359. }
  73360. }
  73361. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  73362. /**
  73363. * Get/set the minimum yaw angle that the bone can look to.
  73364. */
  73365. get: function () {
  73366. return this._minYaw;
  73367. },
  73368. set: function (value) {
  73369. this._minYaw = value;
  73370. this._minYawSin = Math.sin(value);
  73371. this._minYawCos = Math.cos(value);
  73372. if (this._maxYaw != null) {
  73373. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  73374. this._yawRange = this._maxYaw - this._minYaw;
  73375. }
  73376. },
  73377. enumerable: true,
  73378. configurable: true
  73379. });
  73380. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  73381. /**
  73382. * Get/set the maximum yaw angle that the bone can look to.
  73383. */
  73384. get: function () {
  73385. return this._maxYaw;
  73386. },
  73387. set: function (value) {
  73388. this._maxYaw = value;
  73389. this._maxYawSin = Math.sin(value);
  73390. this._maxYawCos = Math.cos(value);
  73391. if (this._minYaw != null) {
  73392. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  73393. this._yawRange = this._maxYaw - this._minYaw;
  73394. }
  73395. },
  73396. enumerable: true,
  73397. configurable: true
  73398. });
  73399. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  73400. /**
  73401. * Get/set the minimum pitch angle that the bone can look to.
  73402. */
  73403. get: function () {
  73404. return this._minPitch;
  73405. },
  73406. set: function (value) {
  73407. this._minPitch = value;
  73408. this._minPitchTan = Math.tan(value);
  73409. },
  73410. enumerable: true,
  73411. configurable: true
  73412. });
  73413. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  73414. /**
  73415. * Get/set the maximum pitch angle that the bone can look to.
  73416. */
  73417. get: function () {
  73418. return this._maxPitch;
  73419. },
  73420. set: function (value) {
  73421. this._maxPitch = value;
  73422. this._maxPitchTan = Math.tan(value);
  73423. },
  73424. enumerable: true,
  73425. configurable: true
  73426. });
  73427. /**
  73428. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  73429. */
  73430. BoneLookController.prototype.update = function () {
  73431. //skip the first frame when slerping so that the mesh rotation is correct
  73432. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  73433. this._firstFrameSkipped = true;
  73434. return;
  73435. }
  73436. var bone = this.bone;
  73437. var bonePos = BoneLookController._tmpVecs[0];
  73438. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  73439. var target = this.target;
  73440. var _tmpMat1 = BoneLookController._tmpMats[0];
  73441. var _tmpMat2 = BoneLookController._tmpMats[1];
  73442. var mesh = this.mesh;
  73443. var parentBone = bone.getParent();
  73444. var upAxis = BoneLookController._tmpVecs[1];
  73445. upAxis.copyFrom(this.upAxis);
  73446. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  73447. if (this._transformYawPitch) {
  73448. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  73449. }
  73450. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  73451. }
  73452. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  73453. mesh.getDirectionToRef(upAxis, upAxis);
  73454. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  73455. upAxis.normalize();
  73456. }
  73457. }
  73458. var checkYaw = false;
  73459. var checkPitch = false;
  73460. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  73461. checkYaw = true;
  73462. }
  73463. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  73464. checkPitch = true;
  73465. }
  73466. if (checkYaw || checkPitch) {
  73467. var spaceMat = BoneLookController._tmpMats[2];
  73468. var spaceMatInv = BoneLookController._tmpMats[3];
  73469. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  73470. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  73471. }
  73472. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  73473. spaceMat.copyFrom(mesh.getWorldMatrix());
  73474. }
  73475. else {
  73476. var forwardAxis = BoneLookController._tmpVecs[2];
  73477. forwardAxis.copyFrom(this._fowardAxis);
  73478. if (this._transformYawPitch) {
  73479. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  73480. }
  73481. if (parentBone) {
  73482. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  73483. }
  73484. else {
  73485. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  73486. }
  73487. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  73488. rightAxis.normalize();
  73489. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  73490. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  73491. }
  73492. spaceMat.invertToRef(spaceMatInv);
  73493. var xzlen = null;
  73494. if (checkPitch) {
  73495. var localTarget = BoneLookController._tmpVecs[3];
  73496. target.subtractToRef(bonePos, localTarget);
  73497. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  73498. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  73499. var pitch = Math.atan2(localTarget.y, xzlen);
  73500. var newPitch = pitch;
  73501. if (pitch > this._maxPitch) {
  73502. localTarget.y = this._maxPitchTan * xzlen;
  73503. newPitch = this._maxPitch;
  73504. }
  73505. else if (pitch < this._minPitch) {
  73506. localTarget.y = this._minPitchTan * xzlen;
  73507. newPitch = this._minPitch;
  73508. }
  73509. if (pitch != newPitch) {
  73510. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  73511. localTarget.addInPlace(bonePos);
  73512. target = localTarget;
  73513. }
  73514. }
  73515. if (checkYaw) {
  73516. var localTarget = BoneLookController._tmpVecs[4];
  73517. target.subtractToRef(bonePos, localTarget);
  73518. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  73519. var yaw = Math.atan2(localTarget.x, localTarget.z);
  73520. var newYaw = yaw;
  73521. if (yaw > this._maxYaw || yaw < this._minYaw) {
  73522. if (xzlen == null) {
  73523. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  73524. }
  73525. if (this._yawRange > Math.PI) {
  73526. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  73527. localTarget.z = this._maxYawCos * xzlen;
  73528. localTarget.x = this._maxYawSin * xzlen;
  73529. newYaw = this._maxYaw;
  73530. }
  73531. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  73532. localTarget.z = this._minYawCos * xzlen;
  73533. localTarget.x = this._minYawSin * xzlen;
  73534. newYaw = this._minYaw;
  73535. }
  73536. }
  73537. else {
  73538. if (yaw > this._maxYaw) {
  73539. localTarget.z = this._maxYawCos * xzlen;
  73540. localTarget.x = this._maxYawSin * xzlen;
  73541. newYaw = this._maxYaw;
  73542. }
  73543. else if (yaw < this._minYaw) {
  73544. localTarget.z = this._minYawCos * xzlen;
  73545. localTarget.x = this._minYawSin * xzlen;
  73546. newYaw = this._minYaw;
  73547. }
  73548. }
  73549. }
  73550. if (this._slerping && this._yawRange > Math.PI) {
  73551. //are we going to be crossing into the min/max region?
  73552. var boneFwd = BoneLookController._tmpVecs[8];
  73553. boneFwd.copyFrom(BABYLON.Axis.Z);
  73554. if (this._transformYawPitch) {
  73555. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  73556. }
  73557. var boneRotMat = BoneLookController._tmpMats[4];
  73558. this._boneQuat.toRotationMatrix(boneRotMat);
  73559. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  73560. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  73561. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  73562. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  73563. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  73564. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  73565. if (angBtwTar > angBtwMidYaw) {
  73566. if (xzlen == null) {
  73567. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  73568. }
  73569. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  73570. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  73571. if (angBtwMin < angBtwMax) {
  73572. newYaw = boneYaw + Math.PI * .75;
  73573. localTarget.z = Math.cos(newYaw) * xzlen;
  73574. localTarget.x = Math.sin(newYaw) * xzlen;
  73575. }
  73576. else {
  73577. newYaw = boneYaw - Math.PI * .75;
  73578. localTarget.z = Math.cos(newYaw) * xzlen;
  73579. localTarget.x = Math.sin(newYaw) * xzlen;
  73580. }
  73581. }
  73582. }
  73583. if (yaw != newYaw) {
  73584. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  73585. localTarget.addInPlace(bonePos);
  73586. target = localTarget;
  73587. }
  73588. }
  73589. }
  73590. var zaxis = BoneLookController._tmpVecs[5];
  73591. var xaxis = BoneLookController._tmpVecs[6];
  73592. var yaxis = BoneLookController._tmpVecs[7];
  73593. var _tmpQuat = BoneLookController._tmpQuat;
  73594. target.subtractToRef(bonePos, zaxis);
  73595. zaxis.normalize();
  73596. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  73597. xaxis.normalize();
  73598. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  73599. yaxis.normalize();
  73600. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  73601. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  73602. return;
  73603. }
  73604. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  73605. return;
  73606. }
  73607. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  73608. return;
  73609. }
  73610. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  73611. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  73612. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  73613. }
  73614. if (this.slerpAmount < 1) {
  73615. if (!this._slerping) {
  73616. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  73617. }
  73618. if (this._transformYawPitch) {
  73619. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  73620. }
  73621. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  73622. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  73623. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  73624. this._slerping = true;
  73625. }
  73626. else {
  73627. if (this._transformYawPitch) {
  73628. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  73629. }
  73630. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  73631. this._slerping = false;
  73632. }
  73633. };
  73634. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  73635. var angDiff = ang2 - ang1;
  73636. angDiff %= Math.PI * 2;
  73637. if (angDiff > Math.PI) {
  73638. angDiff -= Math.PI * 2;
  73639. }
  73640. else if (angDiff < -Math.PI) {
  73641. angDiff += Math.PI * 2;
  73642. }
  73643. return angDiff;
  73644. };
  73645. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  73646. ang1 %= (2 * Math.PI);
  73647. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  73648. ang2 %= (2 * Math.PI);
  73649. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  73650. var ab = 0;
  73651. if (ang1 < ang2) {
  73652. ab = ang2 - ang1;
  73653. }
  73654. else {
  73655. ab = ang1 - ang2;
  73656. }
  73657. if (ab > Math.PI) {
  73658. ab = Math.PI * 2 - ab;
  73659. }
  73660. return ab;
  73661. };
  73662. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  73663. ang %= (2 * Math.PI);
  73664. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  73665. ang1 %= (2 * Math.PI);
  73666. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  73667. ang2 %= (2 * Math.PI);
  73668. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  73669. if (ang1 < ang2) {
  73670. if (ang > ang1 && ang < ang2) {
  73671. return true;
  73672. }
  73673. }
  73674. else {
  73675. if (ang > ang2 && ang < ang1) {
  73676. return true;
  73677. }
  73678. }
  73679. return false;
  73680. };
  73681. 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()];
  73682. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  73683. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  73684. return BoneLookController;
  73685. }());
  73686. BABYLON.BoneLookController = BoneLookController;
  73687. })(BABYLON || (BABYLON = {}));
  73688. //# sourceMappingURL=babylon.boneLookController.js.map
  73689. "use strict";
  73690. var BABYLON;
  73691. (function (BABYLON) {
  73692. var Skeleton = /** @class */ (function () {
  73693. function Skeleton(name, id, scene) {
  73694. this.name = name;
  73695. this.id = id;
  73696. this.bones = new Array();
  73697. this.needInitialSkinMatrix = false;
  73698. this._isDirty = true;
  73699. this._meshesWithPoseMatrix = new Array();
  73700. this._identity = BABYLON.Matrix.Identity();
  73701. this._ranges = {};
  73702. this._lastAbsoluteTransformsUpdateId = -1;
  73703. /**
  73704. * Specifies if the skeleton should be serialized.
  73705. */
  73706. this.doNotSerialize = false;
  73707. // Events
  73708. /**
  73709. * An event triggered before computing the skeleton's matrices
  73710. * @type {BABYLON.Observable}
  73711. */
  73712. this.onBeforeComputeObservable = new BABYLON.Observable();
  73713. this.bones = [];
  73714. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  73715. scene.skeletons.push(this);
  73716. //make sure it will recalculate the matrix next time prepare is called.
  73717. this._isDirty = true;
  73718. }
  73719. // Members
  73720. Skeleton.prototype.getTransformMatrices = function (mesh) {
  73721. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  73722. return mesh._bonesTransformMatrices;
  73723. }
  73724. if (!this._transformMatrices) {
  73725. this.prepare();
  73726. }
  73727. return this._transformMatrices;
  73728. };
  73729. Skeleton.prototype.getScene = function () {
  73730. return this._scene;
  73731. };
  73732. // Methods
  73733. /**
  73734. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  73735. */
  73736. Skeleton.prototype.toString = function (fullDetails) {
  73737. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  73738. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  73739. if (fullDetails) {
  73740. ret += ", Ranges: {";
  73741. var first = true;
  73742. for (var name_1 in this._ranges) {
  73743. if (first) {
  73744. ret += ", ";
  73745. first = false;
  73746. }
  73747. ret += name_1;
  73748. }
  73749. ret += "}";
  73750. }
  73751. return ret;
  73752. };
  73753. /**
  73754. * Get bone's index searching by name
  73755. * @param {string} name is bone's name to search for
  73756. * @return {number} Indice of the bone. Returns -1 if not found
  73757. */
  73758. Skeleton.prototype.getBoneIndexByName = function (name) {
  73759. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  73760. if (this.bones[boneIndex].name === name) {
  73761. return boneIndex;
  73762. }
  73763. }
  73764. return -1;
  73765. };
  73766. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  73767. // check name not already in use
  73768. if (!this._ranges[name]) {
  73769. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  73770. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  73771. if (this.bones[i].animations[0]) {
  73772. this.bones[i].animations[0].createRange(name, from, to);
  73773. }
  73774. }
  73775. }
  73776. };
  73777. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  73778. if (deleteFrames === void 0) { deleteFrames = true; }
  73779. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  73780. if (this.bones[i].animations[0]) {
  73781. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  73782. }
  73783. }
  73784. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  73785. };
  73786. Skeleton.prototype.getAnimationRange = function (name) {
  73787. return this._ranges[name];
  73788. };
  73789. /**
  73790. * Returns as an Array, all AnimationRanges defined on this skeleton
  73791. */
  73792. Skeleton.prototype.getAnimationRanges = function () {
  73793. var animationRanges = [];
  73794. var name;
  73795. var i = 0;
  73796. for (name in this._ranges) {
  73797. animationRanges[i] = this._ranges[name];
  73798. i++;
  73799. }
  73800. return animationRanges;
  73801. };
  73802. /**
  73803. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  73804. */
  73805. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  73806. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  73807. if (this._ranges[name] || !source.getAnimationRange(name)) {
  73808. return false;
  73809. }
  73810. var ret = true;
  73811. var frameOffset = this._getHighestAnimationFrame() + 1;
  73812. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  73813. var boneDict = {};
  73814. var sourceBones = source.bones;
  73815. var nBones;
  73816. var i;
  73817. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  73818. boneDict[sourceBones[i].name] = sourceBones[i];
  73819. }
  73820. if (this.bones.length !== sourceBones.length) {
  73821. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  73822. ret = false;
  73823. }
  73824. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  73825. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  73826. var boneName = this.bones[i].name;
  73827. var sourceBone = boneDict[boneName];
  73828. if (sourceBone) {
  73829. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  73830. }
  73831. else {
  73832. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  73833. ret = false;
  73834. }
  73835. }
  73836. // do not call createAnimationRange(), since it also is done to bones, which was already done
  73837. var range = source.getAnimationRange(name);
  73838. if (range) {
  73839. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  73840. }
  73841. return ret;
  73842. };
  73843. Skeleton.prototype.returnToRest = function () {
  73844. for (var index = 0; index < this.bones.length; index++) {
  73845. this.bones[index].returnToRest();
  73846. }
  73847. };
  73848. Skeleton.prototype._getHighestAnimationFrame = function () {
  73849. var ret = 0;
  73850. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  73851. if (this.bones[i].animations[0]) {
  73852. var highest = this.bones[i].animations[0].getHighestFrame();
  73853. if (ret < highest) {
  73854. ret = highest;
  73855. }
  73856. }
  73857. }
  73858. return ret;
  73859. };
  73860. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  73861. var range = this.getAnimationRange(name);
  73862. if (!range) {
  73863. return null;
  73864. }
  73865. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  73866. };
  73867. Skeleton.prototype._markAsDirty = function () {
  73868. this._isDirty = true;
  73869. };
  73870. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  73871. this._meshesWithPoseMatrix.push(mesh);
  73872. };
  73873. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  73874. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  73875. if (index > -1) {
  73876. this._meshesWithPoseMatrix.splice(index, 1);
  73877. }
  73878. };
  73879. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  73880. this.onBeforeComputeObservable.notifyObservers(this);
  73881. for (var index = 0; index < this.bones.length; index++) {
  73882. var bone = this.bones[index];
  73883. var parentBone = bone.getParent();
  73884. if (parentBone) {
  73885. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  73886. }
  73887. else {
  73888. if (initialSkinMatrix) {
  73889. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  73890. }
  73891. else {
  73892. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  73893. }
  73894. }
  73895. if (bone._index !== -1) {
  73896. var mappedIndex = bone._index === null ? index : bone._index;
  73897. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  73898. }
  73899. }
  73900. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  73901. };
  73902. Skeleton.prototype.prepare = function () {
  73903. if (!this._isDirty) {
  73904. return;
  73905. }
  73906. if (this.needInitialSkinMatrix) {
  73907. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  73908. var mesh = this._meshesWithPoseMatrix[index];
  73909. var poseMatrix = mesh.getPoseMatrix();
  73910. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  73911. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  73912. }
  73913. if (this._synchronizedWithMesh !== mesh) {
  73914. this._synchronizedWithMesh = mesh;
  73915. // Prepare bones
  73916. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  73917. var bone = this.bones[boneIndex];
  73918. if (!bone.getParent()) {
  73919. var matrix = bone.getBaseMatrix();
  73920. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  73921. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  73922. }
  73923. }
  73924. }
  73925. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  73926. }
  73927. }
  73928. else {
  73929. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  73930. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  73931. }
  73932. this._computeTransformMatrices(this._transformMatrices, null);
  73933. }
  73934. this._isDirty = false;
  73935. this._scene._activeBones.addCount(this.bones.length, false);
  73936. };
  73937. Skeleton.prototype.getAnimatables = function () {
  73938. if (!this._animatables || this._animatables.length !== this.bones.length) {
  73939. this._animatables = [];
  73940. for (var index = 0; index < this.bones.length; index++) {
  73941. this._animatables.push(this.bones[index]);
  73942. }
  73943. }
  73944. return this._animatables;
  73945. };
  73946. Skeleton.prototype.clone = function (name, id) {
  73947. var result = new Skeleton(name, id || name, this._scene);
  73948. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  73949. for (var index = 0; index < this.bones.length; index++) {
  73950. var source = this.bones[index];
  73951. var parentBone = null;
  73952. var parent_1 = source.getParent();
  73953. if (parent_1) {
  73954. var parentIndex = this.bones.indexOf(parent_1);
  73955. parentBone = result.bones[parentIndex];
  73956. }
  73957. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  73958. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  73959. }
  73960. if (this._ranges) {
  73961. result._ranges = {};
  73962. for (var rangeName in this._ranges) {
  73963. var range = this._ranges[rangeName];
  73964. if (range) {
  73965. result._ranges[rangeName] = range.clone();
  73966. }
  73967. }
  73968. }
  73969. this._isDirty = true;
  73970. return result;
  73971. };
  73972. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  73973. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  73974. this.bones.forEach(function (bone) {
  73975. bone.animations.forEach(function (animation) {
  73976. animation.enableBlending = true;
  73977. animation.blendingSpeed = blendingSpeed;
  73978. });
  73979. });
  73980. };
  73981. Skeleton.prototype.dispose = function () {
  73982. this._meshesWithPoseMatrix = [];
  73983. // Animations
  73984. this.getScene().stopAnimation(this);
  73985. // Remove from scene
  73986. this.getScene().removeSkeleton(this);
  73987. };
  73988. Skeleton.prototype.serialize = function () {
  73989. var serializationObject = {};
  73990. serializationObject.name = this.name;
  73991. serializationObject.id = this.id;
  73992. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  73993. serializationObject.bones = [];
  73994. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  73995. for (var index = 0; index < this.bones.length; index++) {
  73996. var bone = this.bones[index];
  73997. var parent_2 = bone.getParent();
  73998. var serializedBone = {
  73999. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  74000. name: bone.name,
  74001. matrix: bone.getBaseMatrix().toArray(),
  74002. rest: bone.getRestPose().toArray()
  74003. };
  74004. serializationObject.bones.push(serializedBone);
  74005. if (bone.length) {
  74006. serializedBone.length = bone.length;
  74007. }
  74008. if (bone.animations && bone.animations.length > 0) {
  74009. serializedBone.animation = bone.animations[0].serialize();
  74010. }
  74011. serializationObject.ranges = [];
  74012. for (var name in this._ranges) {
  74013. var source = this._ranges[name];
  74014. if (!source) {
  74015. continue;
  74016. }
  74017. var range = {};
  74018. range.name = name;
  74019. range.from = source.from;
  74020. range.to = source.to;
  74021. serializationObject.ranges.push(range);
  74022. }
  74023. }
  74024. return serializationObject;
  74025. };
  74026. Skeleton.Parse = function (parsedSkeleton, scene) {
  74027. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  74028. if (parsedSkeleton.dimensionsAtRest) {
  74029. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  74030. }
  74031. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  74032. var index;
  74033. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  74034. var parsedBone = parsedSkeleton.bones[index];
  74035. var parentBone = null;
  74036. if (parsedBone.parentBoneIndex > -1) {
  74037. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  74038. }
  74039. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  74040. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  74041. if (parsedBone.length) {
  74042. bone.length = parsedBone.length;
  74043. }
  74044. if (parsedBone.animation) {
  74045. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  74046. }
  74047. }
  74048. // placed after bones, so createAnimationRange can cascade down
  74049. if (parsedSkeleton.ranges) {
  74050. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  74051. var data = parsedSkeleton.ranges[index];
  74052. skeleton.createAnimationRange(data.name, data.from, data.to);
  74053. }
  74054. }
  74055. return skeleton;
  74056. };
  74057. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  74058. if (forceUpdate === void 0) { forceUpdate = false; }
  74059. var renderId = this._scene.getRenderId();
  74060. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  74061. this.bones[0].computeAbsoluteTransforms();
  74062. this._lastAbsoluteTransformsUpdateId = renderId;
  74063. }
  74064. };
  74065. Skeleton.prototype.getPoseMatrix = function () {
  74066. var poseMatrix = null;
  74067. if (this._meshesWithPoseMatrix.length > 0) {
  74068. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  74069. }
  74070. return poseMatrix;
  74071. };
  74072. Skeleton.prototype.sortBones = function () {
  74073. var bones = new Array();
  74074. var visited = new Array(this.bones.length);
  74075. for (var index = 0; index < this.bones.length; index++) {
  74076. this._sortBones(index, bones, visited);
  74077. }
  74078. this.bones = bones;
  74079. };
  74080. Skeleton.prototype._sortBones = function (index, bones, visited) {
  74081. if (visited[index]) {
  74082. return;
  74083. }
  74084. visited[index] = true;
  74085. var bone = this.bones[index];
  74086. if (bone._index === undefined) {
  74087. bone._index = index;
  74088. }
  74089. var parentBone = bone.getParent();
  74090. if (parentBone) {
  74091. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  74092. }
  74093. bones.push(bone);
  74094. };
  74095. return Skeleton;
  74096. }());
  74097. BABYLON.Skeleton = Skeleton;
  74098. })(BABYLON || (BABYLON = {}));
  74099. //# sourceMappingURL=babylon.skeleton.js.map
  74100. "use strict";
  74101. var BABYLON;
  74102. (function (BABYLON) {
  74103. var SphericalPolynomial = /** @class */ (function () {
  74104. function SphericalPolynomial() {
  74105. this.x = BABYLON.Vector3.Zero();
  74106. this.y = BABYLON.Vector3.Zero();
  74107. this.z = BABYLON.Vector3.Zero();
  74108. this.xx = BABYLON.Vector3.Zero();
  74109. this.yy = BABYLON.Vector3.Zero();
  74110. this.zz = BABYLON.Vector3.Zero();
  74111. this.xy = BABYLON.Vector3.Zero();
  74112. this.yz = BABYLON.Vector3.Zero();
  74113. this.zx = BABYLON.Vector3.Zero();
  74114. }
  74115. SphericalPolynomial.prototype.addAmbient = function (color) {
  74116. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  74117. this.xx = this.xx.add(colorVector);
  74118. this.yy = this.yy.add(colorVector);
  74119. this.zz = this.zz.add(colorVector);
  74120. };
  74121. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  74122. var result = new SphericalPolynomial();
  74123. result.x = harmonics.L11.scale(1.02333);
  74124. result.y = harmonics.L1_1.scale(1.02333);
  74125. result.z = harmonics.L10.scale(1.02333);
  74126. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  74127. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  74128. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  74129. result.yz = harmonics.L2_1.scale(0.858086);
  74130. result.zx = harmonics.L21.scale(0.858086);
  74131. result.xy = harmonics.L2_2.scale(0.858086);
  74132. result.scale(1.0 / Math.PI);
  74133. return result;
  74134. };
  74135. SphericalPolynomial.prototype.scale = function (scale) {
  74136. this.x = this.x.scale(scale);
  74137. this.y = this.y.scale(scale);
  74138. this.z = this.z.scale(scale);
  74139. this.xx = this.xx.scale(scale);
  74140. this.yy = this.yy.scale(scale);
  74141. this.zz = this.zz.scale(scale);
  74142. this.yz = this.yz.scale(scale);
  74143. this.zx = this.zx.scale(scale);
  74144. this.xy = this.xy.scale(scale);
  74145. };
  74146. return SphericalPolynomial;
  74147. }());
  74148. BABYLON.SphericalPolynomial = SphericalPolynomial;
  74149. var SphericalHarmonics = /** @class */ (function () {
  74150. function SphericalHarmonics() {
  74151. this.L00 = BABYLON.Vector3.Zero();
  74152. this.L1_1 = BABYLON.Vector3.Zero();
  74153. this.L10 = BABYLON.Vector3.Zero();
  74154. this.L11 = BABYLON.Vector3.Zero();
  74155. this.L2_2 = BABYLON.Vector3.Zero();
  74156. this.L2_1 = BABYLON.Vector3.Zero();
  74157. this.L20 = BABYLON.Vector3.Zero();
  74158. this.L21 = BABYLON.Vector3.Zero();
  74159. this.L22 = BABYLON.Vector3.Zero();
  74160. }
  74161. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  74162. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  74163. var c = colorVector.scale(deltaSolidAngle);
  74164. this.L00 = this.L00.add(c.scale(0.282095));
  74165. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  74166. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  74167. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  74168. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  74169. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  74170. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  74171. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  74172. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  74173. };
  74174. SphericalHarmonics.prototype.scale = function (scale) {
  74175. this.L00 = this.L00.scale(scale);
  74176. this.L1_1 = this.L1_1.scale(scale);
  74177. this.L10 = this.L10.scale(scale);
  74178. this.L11 = this.L11.scale(scale);
  74179. this.L2_2 = this.L2_2.scale(scale);
  74180. this.L2_1 = this.L2_1.scale(scale);
  74181. this.L20 = this.L20.scale(scale);
  74182. this.L21 = this.L21.scale(scale);
  74183. this.L22 = this.L22.scale(scale);
  74184. };
  74185. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  74186. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  74187. //
  74188. // E_lm = A_l * L_lm
  74189. //
  74190. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  74191. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  74192. // the scaling factors are given in equation 9.
  74193. // Constant (Band 0)
  74194. this.L00 = this.L00.scale(3.141593);
  74195. // Linear (Band 1)
  74196. this.L1_1 = this.L1_1.scale(2.094395);
  74197. this.L10 = this.L10.scale(2.094395);
  74198. this.L11 = this.L11.scale(2.094395);
  74199. // Quadratic (Band 2)
  74200. this.L2_2 = this.L2_2.scale(0.785398);
  74201. this.L2_1 = this.L2_1.scale(0.785398);
  74202. this.L20 = this.L20.scale(0.785398);
  74203. this.L21 = this.L21.scale(0.785398);
  74204. this.L22 = this.L22.scale(0.785398);
  74205. };
  74206. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  74207. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  74208. // L = (1/pi) * E * rho
  74209. //
  74210. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  74211. this.scale(1.0 / Math.PI);
  74212. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  74213. // (The pixel shader must apply albedo after texture fetches, etc).
  74214. };
  74215. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  74216. var result = new SphericalHarmonics();
  74217. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  74218. result.L1_1 = polynomial.y.scale(0.977204);
  74219. result.L10 = polynomial.z.scale(0.977204);
  74220. result.L11 = polynomial.x.scale(0.977204);
  74221. result.L2_2 = polynomial.xy.scale(1.16538);
  74222. result.L2_1 = polynomial.yz.scale(1.16538);
  74223. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  74224. result.L21 = polynomial.zx.scale(1.16538);
  74225. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  74226. result.scale(Math.PI);
  74227. return result;
  74228. };
  74229. return SphericalHarmonics;
  74230. }());
  74231. BABYLON.SphericalHarmonics = SphericalHarmonics;
  74232. })(BABYLON || (BABYLON = {}));
  74233. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  74234. "use strict";
  74235. var BABYLON;
  74236. (function (BABYLON) {
  74237. var FileFaceOrientation = /** @class */ (function () {
  74238. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  74239. this.name = name;
  74240. this.worldAxisForNormal = worldAxisForNormal;
  74241. this.worldAxisForFileX = worldAxisForFileX;
  74242. this.worldAxisForFileY = worldAxisForFileY;
  74243. }
  74244. return FileFaceOrientation;
  74245. }());
  74246. ;
  74247. /**
  74248. * Helper class dealing with the extraction of spherical polynomial dataArray
  74249. * from a cube map.
  74250. */
  74251. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  74252. function CubeMapToSphericalPolynomialTools() {
  74253. }
  74254. /**
  74255. * Converts a texture to the according Spherical Polynomial data.
  74256. * This extracts the first 3 orders only as they are the only one used in the lighting.
  74257. *
  74258. * @param texture The texture to extract the information from.
  74259. * @return The Spherical Polynomial data.
  74260. */
  74261. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  74262. if (!texture.isCube) {
  74263. // Only supports cube Textures currently.
  74264. return null;
  74265. }
  74266. var size = texture.getSize().width;
  74267. var right = texture.readPixels(0);
  74268. var left = texture.readPixels(1);
  74269. var up;
  74270. var down;
  74271. if (texture.isRenderTarget) {
  74272. up = texture.readPixels(3);
  74273. down = texture.readPixels(2);
  74274. }
  74275. else {
  74276. up = texture.readPixels(2);
  74277. down = texture.readPixels(3);
  74278. }
  74279. var front = texture.readPixels(4);
  74280. var back = texture.readPixels(5);
  74281. var gammaSpace = texture.gammaSpace;
  74282. // Always read as RGBA.
  74283. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  74284. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  74285. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  74286. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  74287. }
  74288. var cubeInfo = {
  74289. size: size,
  74290. right: right,
  74291. left: left,
  74292. up: up,
  74293. down: down,
  74294. front: front,
  74295. back: back,
  74296. format: format,
  74297. type: type,
  74298. gammaSpace: gammaSpace,
  74299. };
  74300. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  74301. };
  74302. /**
  74303. * Converts a cubemap to the according Spherical Polynomial data.
  74304. * This extracts the first 3 orders only as they are the only one used in the lighting.
  74305. *
  74306. * @param cubeInfo The Cube map to extract the information from.
  74307. * @return The Spherical Polynomial data.
  74308. */
  74309. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  74310. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  74311. var totalSolidAngle = 0.0;
  74312. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  74313. var du = 2.0 / cubeInfo.size;
  74314. var dv = du;
  74315. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  74316. var minUV = du * 0.5 - 1.0;
  74317. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  74318. var fileFace = this.FileFaces[faceIndex];
  74319. var dataArray = cubeInfo[fileFace.name];
  74320. var v = minUV;
  74321. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  74322. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  74323. // Because SP is still linear, so summation is fine in that basis.
  74324. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  74325. for (var y = 0; y < cubeInfo.size; y++) {
  74326. var u = minUV;
  74327. for (var x = 0; x < cubeInfo.size; x++) {
  74328. // World direction (not normalised)
  74329. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  74330. worldDirection.normalize();
  74331. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  74332. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  74333. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  74334. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  74335. // Handle Integer types.
  74336. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  74337. r /= 255;
  74338. g /= 255;
  74339. b /= 255;
  74340. }
  74341. // Handle Gamma space textures.
  74342. if (cubeInfo.gammaSpace) {
  74343. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  74344. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  74345. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  74346. }
  74347. var color = new BABYLON.Color3(r, g, b);
  74348. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  74349. totalSolidAngle += deltaSolidAngle;
  74350. u += du;
  74351. }
  74352. v += dv;
  74353. }
  74354. }
  74355. // Solid angle for entire sphere is 4*pi
  74356. var sphereSolidAngle = 4.0 * Math.PI;
  74357. // Adjust the solid angle to allow for how many faces we processed.
  74358. var facesProcessed = 6.0;
  74359. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  74360. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  74361. // This is needed because the numerical integration over the cube uses a
  74362. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  74363. // and also to compensate for accumulative error due to float precision in the summation.
  74364. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  74365. sphericalHarmonics.scale(correctionFactor);
  74366. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  74367. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  74368. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  74369. };
  74370. CubeMapToSphericalPolynomialTools.FileFaces = [
  74371. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  74372. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  74373. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  74374. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  74375. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  74376. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  74377. ];
  74378. return CubeMapToSphericalPolynomialTools;
  74379. }());
  74380. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  74381. })(BABYLON || (BABYLON = {}));
  74382. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  74383. "use strict";
  74384. var BABYLON;
  74385. (function (BABYLON) {
  74386. /**
  74387. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  74388. */
  74389. var PanoramaToCubeMapTools = /** @class */ (function () {
  74390. function PanoramaToCubeMapTools() {
  74391. }
  74392. /**
  74393. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  74394. *
  74395. * @param float32Array The source data.
  74396. * @param inputWidth The width of the input panorama.
  74397. * @param inputhHeight The height of the input panorama.
  74398. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  74399. * @return The cubemap data
  74400. */
  74401. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  74402. if (!float32Array) {
  74403. throw "ConvertPanoramaToCubemap: input cannot be null";
  74404. }
  74405. if (float32Array.length != inputWidth * inputHeight * 3) {
  74406. throw "ConvertPanoramaToCubemap: input size is wrong";
  74407. }
  74408. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  74409. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  74410. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  74411. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  74412. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  74413. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  74414. return {
  74415. front: textureFront,
  74416. back: textureBack,
  74417. left: textureLeft,
  74418. right: textureRight,
  74419. up: textureUp,
  74420. down: textureDown,
  74421. size: size,
  74422. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  74423. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  74424. gammaSpace: false,
  74425. };
  74426. };
  74427. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  74428. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  74429. var textureArray = new Float32Array(buffer);
  74430. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  74431. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  74432. var dy = 1 / texSize;
  74433. var fy = 0;
  74434. for (var y = 0; y < texSize; y++) {
  74435. var xv1 = faceData[0];
  74436. var xv2 = faceData[2];
  74437. for (var x = 0; x < texSize; x++) {
  74438. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  74439. v.normalize();
  74440. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  74441. // 3 channels per pixels
  74442. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  74443. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  74444. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  74445. xv1 = xv1.add(rotDX1);
  74446. xv2 = xv2.add(rotDX2);
  74447. }
  74448. fy += dy;
  74449. }
  74450. return textureArray;
  74451. };
  74452. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  74453. var theta = Math.atan2(vDir.z, vDir.x);
  74454. var phi = Math.acos(vDir.y);
  74455. while (theta < -Math.PI)
  74456. theta += 2 * Math.PI;
  74457. while (theta > Math.PI)
  74458. theta -= 2 * Math.PI;
  74459. var dx = theta / Math.PI;
  74460. var dy = phi / Math.PI;
  74461. // recenter.
  74462. dx = dx * 0.5 + 0.5;
  74463. var px = Math.round(dx * inputWidth);
  74464. if (px < 0)
  74465. px = 0;
  74466. else if (px >= inputWidth)
  74467. px = inputWidth - 1;
  74468. var py = Math.round(dy * inputHeight);
  74469. if (py < 0)
  74470. py = 0;
  74471. else if (py >= inputHeight)
  74472. py = inputHeight - 1;
  74473. var inputY = (inputHeight - py - 1);
  74474. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  74475. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  74476. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  74477. return {
  74478. r: r,
  74479. g: g,
  74480. b: b
  74481. };
  74482. };
  74483. PanoramaToCubeMapTools.FACE_FRONT = [
  74484. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  74485. new BABYLON.Vector3(1.0, -1.0, -1.0),
  74486. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  74487. new BABYLON.Vector3(1.0, 1.0, -1.0)
  74488. ];
  74489. PanoramaToCubeMapTools.FACE_BACK = [
  74490. new BABYLON.Vector3(1.0, -1.0, 1.0),
  74491. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  74492. new BABYLON.Vector3(1.0, 1.0, 1.0),
  74493. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  74494. ];
  74495. PanoramaToCubeMapTools.FACE_RIGHT = [
  74496. new BABYLON.Vector3(1.0, -1.0, -1.0),
  74497. new BABYLON.Vector3(1.0, -1.0, 1.0),
  74498. new BABYLON.Vector3(1.0, 1.0, -1.0),
  74499. new BABYLON.Vector3(1.0, 1.0, 1.0)
  74500. ];
  74501. PanoramaToCubeMapTools.FACE_LEFT = [
  74502. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  74503. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  74504. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  74505. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  74506. ];
  74507. PanoramaToCubeMapTools.FACE_DOWN = [
  74508. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  74509. new BABYLON.Vector3(1.0, 1.0, -1.0),
  74510. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  74511. new BABYLON.Vector3(1.0, 1.0, 1.0)
  74512. ];
  74513. PanoramaToCubeMapTools.FACE_UP = [
  74514. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  74515. new BABYLON.Vector3(1.0, -1.0, 1.0),
  74516. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  74517. new BABYLON.Vector3(1.0, -1.0, -1.0)
  74518. ];
  74519. return PanoramaToCubeMapTools;
  74520. }());
  74521. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  74522. })(BABYLON || (BABYLON = {}));
  74523. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  74524. "use strict";
  74525. var BABYLON;
  74526. (function (BABYLON) {
  74527. ;
  74528. /**
  74529. * This groups tools to convert HDR texture to native colors array.
  74530. */
  74531. var HDRTools = /** @class */ (function () {
  74532. function HDRTools() {
  74533. }
  74534. HDRTools.Ldexp = function (mantissa, exponent) {
  74535. if (exponent > 1023) {
  74536. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  74537. }
  74538. if (exponent < -1074) {
  74539. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  74540. }
  74541. return mantissa * Math.pow(2, exponent);
  74542. };
  74543. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  74544. if (exponent > 0) {
  74545. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  74546. float32array[index + 0] = red * exponent;
  74547. float32array[index + 1] = green * exponent;
  74548. float32array[index + 2] = blue * exponent;
  74549. }
  74550. else {
  74551. float32array[index + 0] = 0;
  74552. float32array[index + 1] = 0;
  74553. float32array[index + 2] = 0;
  74554. }
  74555. };
  74556. HDRTools.readStringLine = function (uint8array, startIndex) {
  74557. var line = "";
  74558. var character = "";
  74559. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  74560. character = String.fromCharCode(uint8array[i]);
  74561. if (character == "\n") {
  74562. break;
  74563. }
  74564. line += character;
  74565. }
  74566. return line;
  74567. };
  74568. /**
  74569. * Reads header information from an RGBE texture stored in a native array.
  74570. * More information on this format are available here:
  74571. * https://en.wikipedia.org/wiki/RGBE_image_format
  74572. *
  74573. * @param uint8array The binary file stored in native array.
  74574. * @return The header information.
  74575. */
  74576. HDRTools.RGBE_ReadHeader = function (uint8array) {
  74577. var height = 0;
  74578. var width = 0;
  74579. var line = this.readStringLine(uint8array, 0);
  74580. if (line[0] != '#' || line[1] != '?') {
  74581. throw "Bad HDR Format.";
  74582. }
  74583. var endOfHeader = false;
  74584. var findFormat = false;
  74585. var lineIndex = 0;
  74586. do {
  74587. lineIndex += (line.length + 1);
  74588. line = this.readStringLine(uint8array, lineIndex);
  74589. if (line == "FORMAT=32-bit_rle_rgbe") {
  74590. findFormat = true;
  74591. }
  74592. else if (line.length == 0) {
  74593. endOfHeader = true;
  74594. }
  74595. } while (!endOfHeader);
  74596. if (!findFormat) {
  74597. throw "HDR Bad header format, unsupported FORMAT";
  74598. }
  74599. lineIndex += (line.length + 1);
  74600. line = this.readStringLine(uint8array, lineIndex);
  74601. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  74602. var match = sizeRegexp.exec(line);
  74603. // TODO. Support +Y and -X if needed.
  74604. if (!match || match.length < 3) {
  74605. throw "HDR Bad header format, no size";
  74606. }
  74607. width = parseInt(match[2]);
  74608. height = parseInt(match[1]);
  74609. if (width < 8 || width > 0x7fff) {
  74610. throw "HDR Bad header format, unsupported size";
  74611. }
  74612. lineIndex += (line.length + 1);
  74613. return {
  74614. height: height,
  74615. width: width,
  74616. dataPosition: lineIndex
  74617. };
  74618. };
  74619. /**
  74620. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  74621. * This RGBE texture needs to store the information as a panorama.
  74622. *
  74623. * More information on this format are available here:
  74624. * https://en.wikipedia.org/wiki/RGBE_image_format
  74625. *
  74626. * @param buffer The binary file stored in an array buffer.
  74627. * @param size The expected size of the extracted cubemap.
  74628. * @return The Cube Map information.
  74629. */
  74630. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  74631. var uint8array = new Uint8Array(buffer);
  74632. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  74633. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  74634. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  74635. return cubeMapData;
  74636. };
  74637. /**
  74638. * Returns the pixels data extracted from an RGBE texture.
  74639. * This pixels will be stored left to right up to down in the R G B order in one array.
  74640. *
  74641. * More information on this format are available here:
  74642. * https://en.wikipedia.org/wiki/RGBE_image_format
  74643. *
  74644. * @param uint8array The binary file stored in an array buffer.
  74645. * @param hdrInfo The header information of the file.
  74646. * @return The pixels data in RGB right to left up to down order.
  74647. */
  74648. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  74649. // Keep for multi format supports.
  74650. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  74651. };
  74652. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  74653. var num_scanlines = hdrInfo.height;
  74654. var scanline_width = hdrInfo.width;
  74655. var a, b, c, d, count;
  74656. var dataIndex = hdrInfo.dataPosition;
  74657. var index = 0, endIndex = 0, i = 0;
  74658. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  74659. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  74660. // 3 channels of 4 bytes per pixel in float.
  74661. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  74662. var resultArray = new Float32Array(resultBuffer);
  74663. // read in each successive scanline
  74664. while (num_scanlines > 0) {
  74665. a = uint8array[dataIndex++];
  74666. b = uint8array[dataIndex++];
  74667. c = uint8array[dataIndex++];
  74668. d = uint8array[dataIndex++];
  74669. if (a != 2 || b != 2 || (c & 0x80)) {
  74670. // this file is not run length encoded
  74671. throw "HDR Bad header format, not RLE";
  74672. }
  74673. if (((c << 8) | d) != scanline_width) {
  74674. throw "HDR Bad header format, wrong scan line width";
  74675. }
  74676. index = 0;
  74677. // read each of the four channels for the scanline into the buffer
  74678. for (i = 0; i < 4; i++) {
  74679. endIndex = (i + 1) * scanline_width;
  74680. while (index < endIndex) {
  74681. a = uint8array[dataIndex++];
  74682. b = uint8array[dataIndex++];
  74683. if (a > 128) {
  74684. // a run of the same value
  74685. count = a - 128;
  74686. if ((count == 0) || (count > endIndex - index)) {
  74687. throw "HDR Bad Format, bad scanline data (run)";
  74688. }
  74689. while (count-- > 0) {
  74690. scanLineArray[index++] = b;
  74691. }
  74692. }
  74693. else {
  74694. // a non-run
  74695. count = a;
  74696. if ((count == 0) || (count > endIndex - index)) {
  74697. throw "HDR Bad Format, bad scanline data (non-run)";
  74698. }
  74699. scanLineArray[index++] = b;
  74700. if (--count > 0) {
  74701. for (var j = 0; j < count; j++) {
  74702. scanLineArray[index++] = uint8array[dataIndex++];
  74703. }
  74704. }
  74705. }
  74706. }
  74707. }
  74708. // now convert data from buffer into floats
  74709. for (i = 0; i < scanline_width; i++) {
  74710. a = scanLineArray[i];
  74711. b = scanLineArray[i + scanline_width];
  74712. c = scanLineArray[i + 2 * scanline_width];
  74713. d = scanLineArray[i + 3 * scanline_width];
  74714. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  74715. }
  74716. num_scanlines--;
  74717. }
  74718. return resultArray;
  74719. };
  74720. return HDRTools;
  74721. }());
  74722. BABYLON.HDRTools = HDRTools;
  74723. })(BABYLON || (BABYLON = {}));
  74724. //# sourceMappingURL=babylon.hdr.js.map
  74725. "use strict";
  74726. var BABYLON;
  74727. (function (BABYLON) {
  74728. /**
  74729. * This represents a texture coming from an HDR input.
  74730. *
  74731. * The only supported format is currently panorama picture stored in RGBE format.
  74732. * Example of such files can be found on HDRLib: http://hdrlib.com/
  74733. */
  74734. var HDRCubeTexture = /** @class */ (function (_super) {
  74735. __extends(HDRCubeTexture, _super);
  74736. /**
  74737. * Instantiates an HDRTexture from the following parameters.
  74738. *
  74739. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  74740. * @param scene The scene the texture will be used in
  74741. * @param size The cubemap desired size (the more it increases the longer the generation will be) If the size is omitted this implies you are using a preprocessed cubemap.
  74742. * @param noMipmap Forces to not generate the mipmap if true
  74743. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  74744. * @param useInGammaSpace Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space)
  74745. * @param usePMREMGenerator Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  74746. */
  74747. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  74748. if (noMipmap === void 0) { noMipmap = false; }
  74749. if (generateHarmonics === void 0) { generateHarmonics = true; }
  74750. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  74751. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  74752. if (onLoad === void 0) { onLoad = null; }
  74753. if (onError === void 0) { onError = null; }
  74754. var _this = _super.call(this, scene) || this;
  74755. _this._useInGammaSpace = false;
  74756. _this._generateHarmonics = true;
  74757. _this._isBABYLONPreprocessed = false;
  74758. _this._onLoad = null;
  74759. _this._onError = null;
  74760. /**
  74761. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  74762. */
  74763. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  74764. /**
  74765. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  74766. * This is usefull at run time to apply the good shader.
  74767. */
  74768. _this.isPMREM = false;
  74769. _this._isBlocking = true;
  74770. /**
  74771. * Gets or sets the center of the bounding box associated with the cube texture
  74772. * It must define where the camera used to render the texture was set
  74773. */
  74774. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  74775. if (!url) {
  74776. return _this;
  74777. }
  74778. _this.name = url;
  74779. _this.url = url;
  74780. _this.hasAlpha = false;
  74781. _this.isCube = true;
  74782. _this._textureMatrix = BABYLON.Matrix.Identity();
  74783. _this._onLoad = onLoad;
  74784. _this._onError = onError;
  74785. _this.gammaSpace = false;
  74786. var caps = scene.getEngine().getCaps();
  74787. if (size) {
  74788. _this._isBABYLONPreprocessed = false;
  74789. _this._noMipmap = noMipmap;
  74790. _this._size = size;
  74791. _this._useInGammaSpace = useInGammaSpace;
  74792. _this._usePMREMGenerator = usePMREMGenerator &&
  74793. caps.textureLOD &&
  74794. caps.textureFloat &&
  74795. !_this._useInGammaSpace;
  74796. }
  74797. else {
  74798. _this._isBABYLONPreprocessed = true;
  74799. _this._noMipmap = false;
  74800. _this._useInGammaSpace = false;
  74801. _this._usePMREMGenerator = caps.textureLOD && caps.textureFloat &&
  74802. !_this._useInGammaSpace;
  74803. }
  74804. _this.isPMREM = _this._usePMREMGenerator;
  74805. _this._texture = _this._getFromCache(url, _this._noMipmap);
  74806. if (!_this._texture) {
  74807. if (!scene.useDelayedTextureLoading) {
  74808. _this.loadTexture();
  74809. }
  74810. else {
  74811. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  74812. }
  74813. }
  74814. return _this;
  74815. }
  74816. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  74817. /**
  74818. * Gets wether or not the texture is blocking during loading.
  74819. */
  74820. get: function () {
  74821. return this._isBlocking;
  74822. },
  74823. /**
  74824. * Sets wether or not the texture is blocking during loading.
  74825. */
  74826. set: function (value) {
  74827. this._isBlocking = value;
  74828. },
  74829. enumerable: true,
  74830. configurable: true
  74831. });
  74832. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  74833. get: function () {
  74834. return this._boundingBoxSize;
  74835. },
  74836. /**
  74837. * Gets or sets the size of the bounding box associated with the cube texture
  74838. * When defined, the cubemap will switch to local mode
  74839. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  74840. * @example https://www.babylonjs-playground.com/#RNASML
  74841. */
  74842. set: function (value) {
  74843. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  74844. return;
  74845. }
  74846. this._boundingBoxSize = value;
  74847. var scene = this.getScene();
  74848. if (scene) {
  74849. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  74850. }
  74851. },
  74852. enumerable: true,
  74853. configurable: true
  74854. });
  74855. /**
  74856. * Occurs when the file is a preprocessed .babylon.hdr file.
  74857. */
  74858. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  74859. var _this = this;
  74860. var mipLevels = 0;
  74861. var floatArrayView = null;
  74862. var scene = this.getScene();
  74863. var mipmapGenerator = (!this._useInGammaSpace && scene && scene.getEngine().getCaps().textureFloat) ? function (data) {
  74864. var mips = new Array();
  74865. if (!floatArrayView) {
  74866. return mips;
  74867. }
  74868. var startIndex = 30;
  74869. for (var level = 0; level < mipLevels; level++) {
  74870. mips.push([]);
  74871. // Fill each pixel of the mip level.
  74872. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  74873. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  74874. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  74875. mips[level].push(faceData);
  74876. startIndex += faceSize;
  74877. }
  74878. }
  74879. return mips;
  74880. } : null;
  74881. var callback = function (buffer) {
  74882. var scene = _this.getScene();
  74883. if (!scene) {
  74884. return null;
  74885. }
  74886. // Create Native Array Views
  74887. var intArrayView = new Int32Array(buffer);
  74888. floatArrayView = new Float32Array(buffer);
  74889. // Fill header.
  74890. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  74891. _this._size = intArrayView[1]; // CubeMap max mip face size.
  74892. // Update Texture Information.
  74893. if (!_this._texture) {
  74894. return null;
  74895. }
  74896. _this._texture.updateSize(_this._size, _this._size);
  74897. // Fill polynomial information.
  74898. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  74899. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  74900. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  74901. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  74902. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  74903. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  74904. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  74905. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  74906. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  74907. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  74908. _this.sphericalPolynomial = sphericalPolynomial;
  74909. // Fill pixel data.
  74910. mipLevels = intArrayView[29]; // Number of mip levels.
  74911. var startIndex = 30;
  74912. var data = [];
  74913. var faceSize = Math.pow(_this._size, 2) * 3;
  74914. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  74915. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  74916. startIndex += faceSize;
  74917. }
  74918. var results = [];
  74919. var byteArray = null;
  74920. // Push each faces.
  74921. for (var k = 0; k < 6; k++) {
  74922. var dataFace = null;
  74923. // To be deprecated.
  74924. if (version === 1) {
  74925. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  74926. dataFace = data[j];
  74927. }
  74928. // If special cases.
  74929. if (!mipmapGenerator && dataFace) {
  74930. if (!scene.getEngine().getCaps().textureFloat) {
  74931. // 3 channels of 1 bytes per pixel in bytes.
  74932. var byteBuffer = new ArrayBuffer(faceSize);
  74933. byteArray = new Uint8Array(byteBuffer);
  74934. }
  74935. for (var i = 0; i < _this._size * _this._size; i++) {
  74936. // Put in gamma space if requested.
  74937. if (_this._useInGammaSpace) {
  74938. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  74939. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  74940. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  74941. }
  74942. // Convert to int texture for fallback.
  74943. if (byteArray) {
  74944. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  74945. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  74946. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  74947. // May use luminance instead if the result is not accurate.
  74948. var max = Math.max(Math.max(r, g), b);
  74949. if (max > 255) {
  74950. var scale = 255 / max;
  74951. r *= scale;
  74952. g *= scale;
  74953. b *= scale;
  74954. }
  74955. byteArray[(i * 3) + 0] = r;
  74956. byteArray[(i * 3) + 1] = g;
  74957. byteArray[(i * 3) + 2] = b;
  74958. }
  74959. }
  74960. }
  74961. // Fill the array accordingly.
  74962. if (byteArray) {
  74963. results.push(byteArray);
  74964. }
  74965. else {
  74966. results.push(dataFace);
  74967. }
  74968. }
  74969. return results;
  74970. };
  74971. if (scene) {
  74972. this._texture = scene.getEngine().createRawCubeTextureFromUrl(this.url, scene, this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, scene.getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator, this._onLoad, this._onError);
  74973. }
  74974. };
  74975. /**
  74976. * Occurs when the file is raw .hdr file.
  74977. */
  74978. HDRCubeTexture.prototype.loadHDRTexture = function () {
  74979. var _this = this;
  74980. var callback = function (buffer) {
  74981. var scene = _this.getScene();
  74982. if (!scene) {
  74983. return null;
  74984. }
  74985. // Extract the raw linear data.
  74986. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  74987. // Generate harmonics if needed.
  74988. if (_this._generateHarmonics) {
  74989. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  74990. _this.sphericalPolynomial = sphericalPolynomial;
  74991. }
  74992. var results = [];
  74993. var byteArray = null;
  74994. // Push each faces.
  74995. for (var j = 0; j < 6; j++) {
  74996. // Create uintarray fallback.
  74997. if (!scene.getEngine().getCaps().textureFloat) {
  74998. // 3 channels of 1 bytes per pixel in bytes.
  74999. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  75000. byteArray = new Uint8Array(byteBuffer);
  75001. }
  75002. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  75003. // If special cases.
  75004. if (_this._useInGammaSpace || byteArray) {
  75005. for (var i = 0; i < _this._size * _this._size; i++) {
  75006. // Put in gamma space if requested.
  75007. if (_this._useInGammaSpace) {
  75008. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  75009. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  75010. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  75011. }
  75012. // Convert to int texture for fallback.
  75013. if (byteArray) {
  75014. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  75015. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  75016. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  75017. // May use luminance instead if the result is not accurate.
  75018. var max = Math.max(Math.max(r, g), b);
  75019. if (max > 255) {
  75020. var scale = 255 / max;
  75021. r *= scale;
  75022. g *= scale;
  75023. b *= scale;
  75024. }
  75025. byteArray[(i * 3) + 0] = r;
  75026. byteArray[(i * 3) + 1] = g;
  75027. byteArray[(i * 3) + 2] = b;
  75028. }
  75029. }
  75030. }
  75031. if (byteArray) {
  75032. results.push(byteArray);
  75033. }
  75034. else {
  75035. results.push(dataFace);
  75036. }
  75037. }
  75038. return results;
  75039. };
  75040. var mipmapGenerator = null;
  75041. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  75042. // if (!this._noMipmap &&
  75043. // this._usePMREMGenerator) {
  75044. // mipmapGenerator = (data: ArrayBufferView[]) => {
  75045. // // Custom setup of the generator matching with the PBR shader values.
  75046. // var generator = new BABYLON.PMREMGenerator(data,
  75047. // this._size,
  75048. // this._size,
  75049. // 0,
  75050. // 3,
  75051. // this.getScene().getEngine().getCaps().textureFloat,
  75052. // 2048,
  75053. // 0.25,
  75054. // false,
  75055. // true);
  75056. // return generator.filterCubeMap();
  75057. // };
  75058. // }
  75059. var scene = this.getScene();
  75060. if (scene) {
  75061. this._texture = scene.getEngine().createRawCubeTextureFromUrl(this.url, scene, this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, scene.getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator, this._onLoad, this._onError);
  75062. }
  75063. };
  75064. /**
  75065. * Starts the loading process of the texture.
  75066. */
  75067. HDRCubeTexture.prototype.loadTexture = function () {
  75068. if (this._isBABYLONPreprocessed) {
  75069. this.loadBabylonTexture();
  75070. }
  75071. else {
  75072. this.loadHDRTexture();
  75073. }
  75074. };
  75075. HDRCubeTexture.prototype.clone = function () {
  75076. var scene = this.getScene();
  75077. if (!scene) {
  75078. return this;
  75079. }
  75080. var size = (this._isBABYLONPreprocessed ? null : this._size);
  75081. var newTexture = new HDRCubeTexture(this.url, scene, size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  75082. // Base texture
  75083. newTexture.level = this.level;
  75084. newTexture.wrapU = this.wrapU;
  75085. newTexture.wrapV = this.wrapV;
  75086. newTexture.coordinatesIndex = this.coordinatesIndex;
  75087. newTexture.coordinatesMode = this.coordinatesMode;
  75088. return newTexture;
  75089. };
  75090. // Methods
  75091. HDRCubeTexture.prototype.delayLoad = function () {
  75092. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  75093. return;
  75094. }
  75095. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  75096. this._texture = this._getFromCache(this.url, this._noMipmap);
  75097. if (!this._texture) {
  75098. this.loadTexture();
  75099. }
  75100. };
  75101. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  75102. return this._textureMatrix;
  75103. };
  75104. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  75105. this._textureMatrix = value;
  75106. };
  75107. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  75108. var texture = null;
  75109. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  75110. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  75111. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  75112. texture.name = parsedTexture.name;
  75113. texture.hasAlpha = parsedTexture.hasAlpha;
  75114. texture.level = parsedTexture.level;
  75115. texture.coordinatesMode = parsedTexture.coordinatesMode;
  75116. texture.isBlocking = parsedTexture.isBlocking;
  75117. }
  75118. if (texture) {
  75119. if (parsedTexture.boundingBoxPosition) {
  75120. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  75121. }
  75122. if (parsedTexture.boundingBoxSize) {
  75123. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  75124. }
  75125. }
  75126. return texture;
  75127. };
  75128. HDRCubeTexture.prototype.serialize = function () {
  75129. if (!this.name) {
  75130. return null;
  75131. }
  75132. var serializationObject = {};
  75133. serializationObject.name = this.name;
  75134. serializationObject.hasAlpha = this.hasAlpha;
  75135. serializationObject.isCube = true;
  75136. serializationObject.level = this.level;
  75137. serializationObject.size = this._size;
  75138. serializationObject.coordinatesMode = this.coordinatesMode;
  75139. serializationObject.useInGammaSpace = this._useInGammaSpace;
  75140. serializationObject.generateHarmonics = this._generateHarmonics;
  75141. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  75142. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  75143. serializationObject.customType = "BABYLON.HDRCubeTexture";
  75144. serializationObject.noMipmap = this._noMipmap;
  75145. serializationObject.isBlocking = this._isBlocking;
  75146. return serializationObject;
  75147. };
  75148. /**
  75149. * Saves as a file the data contained in the texture in a binary format.
  75150. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  75151. * as the spherical used in the lighting.
  75152. * @param url The HDR file url.
  75153. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  75154. * @param onError Method called if any error happens during download.
  75155. * @return The packed binary data.
  75156. */
  75157. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  75158. if (onError === void 0) { onError = null; }
  75159. var callback = function (buffer) {
  75160. var data = new Blob([buffer], { type: 'application/octet-stream' });
  75161. // Returns a URL you can use as a href.
  75162. var objUrl = window.URL.createObjectURL(data);
  75163. // Simulates a link to it and click to dowload.
  75164. var a = document.createElement("a");
  75165. document.body.appendChild(a);
  75166. a.style.display = "none";
  75167. a.href = objUrl;
  75168. a.download = "envmap.babylon.hdr";
  75169. a.click();
  75170. };
  75171. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  75172. };
  75173. /**
  75174. * Serializes the data contained in the texture in a binary format.
  75175. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  75176. * as the spherical used in the lighting.
  75177. * @param url The HDR file url.
  75178. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  75179. * @param onError Method called if any error happens during download.
  75180. * @return The packed binary data.
  75181. */
  75182. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  75183. if (onError === void 0) { onError = null; }
  75184. // Needs the url tho create the texture.
  75185. if (!url) {
  75186. return;
  75187. }
  75188. // Check Power of two size.
  75189. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  75190. return;
  75191. }
  75192. // Coming Back in 3.x.
  75193. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.2.");
  75194. };
  75195. HDRCubeTexture._facesMapping = [
  75196. "right",
  75197. "left",
  75198. "up",
  75199. "down",
  75200. "front",
  75201. "back"
  75202. ];
  75203. return HDRCubeTexture;
  75204. }(BABYLON.BaseTexture));
  75205. BABYLON.HDRCubeTexture = HDRCubeTexture;
  75206. })(BABYLON || (BABYLON = {}));
  75207. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  75208. "use strict";
  75209. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  75210. // Huge respect for a such great lib.
  75211. // Earcut license:
  75212. // Copyright (c) 2016, Mapbox
  75213. //
  75214. // Permission to use, copy, modify, and/or distribute this software for any purpose
  75215. // with or without fee is hereby granted, provided that the above copyright notice
  75216. // and this permission notice appear in all copies.
  75217. //
  75218. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  75219. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  75220. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  75221. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  75222. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  75223. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  75224. // THIS SOFTWARE.
  75225. var Earcut;
  75226. (function (Earcut) {
  75227. /**
  75228. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  75229. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  75230. * @param holeIndices is an array of hole indices if any (e.g. [5, 8] for a 12- vertice input would mean one hole with vertices 5–7 and another with 8–11).
  75231. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  75232. */
  75233. function earcut(data, holeIndices, dim) {
  75234. dim = dim || 2;
  75235. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = new Array();
  75236. if (!outerNode)
  75237. return triangles;
  75238. var minX = 0, minY = 0, maxX, maxY, x, y, size = 0;
  75239. if (hasHoles)
  75240. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  75241. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  75242. if (data.length > 80 * dim) {
  75243. minX = maxX = data[0];
  75244. minY = maxY = data[1];
  75245. for (var i = dim; i < outerLen; i += dim) {
  75246. x = data[i];
  75247. y = data[i + 1];
  75248. if (x < minX)
  75249. minX = x;
  75250. if (y < minY)
  75251. minY = y;
  75252. if (x > maxX)
  75253. maxX = x;
  75254. if (y > maxY)
  75255. maxY = y;
  75256. }
  75257. // minX, minY and size are later used to transform coords into integers for z-order calculation
  75258. size = Math.max(maxX - minX, maxY - minY);
  75259. }
  75260. earcutLinked(outerNode, triangles, dim, minX, minY, size, 0);
  75261. return triangles;
  75262. }
  75263. Earcut.earcut = earcut;
  75264. var Node = /** @class */ (function () {
  75265. function Node(i, x, y) {
  75266. this.i = i;
  75267. this.x = x;
  75268. this.y = y;
  75269. this.prev = null;
  75270. this.next = null;
  75271. this.z = null;
  75272. this.prevZ = null;
  75273. this.nextZ = null;
  75274. this.steiner = false;
  75275. }
  75276. return Node;
  75277. }());
  75278. // create a circular doubly linked list from polygon points in the specified winding order
  75279. function linkedList(data, start, end, dim, clockwise) {
  75280. var i, last = null;
  75281. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  75282. for (i = start; i < end; i += dim)
  75283. last = insertNode(i, data[i], data[i + 1], last);
  75284. }
  75285. else {
  75286. for (i = end - dim; i >= start; i -= dim)
  75287. last = insertNode(i, data[i], data[i + 1], last);
  75288. }
  75289. if (last && equals(last, last.next)) {
  75290. removeNode(last);
  75291. last = last.next;
  75292. }
  75293. return last;
  75294. }
  75295. // eliminate colinear or duplicate points
  75296. function filterPoints(start, end) {
  75297. if (!start)
  75298. return start;
  75299. if (!end)
  75300. end = start;
  75301. var p = start, again;
  75302. do {
  75303. again = false;
  75304. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  75305. removeNode(p);
  75306. p = end = p.prev;
  75307. if (p === p.next)
  75308. return undefined;
  75309. again = true;
  75310. }
  75311. else {
  75312. p = p.next;
  75313. }
  75314. } while (again || p !== end);
  75315. return end;
  75316. }
  75317. // main ear slicing loop which triangulates a polygon (given as a linked list)
  75318. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  75319. if (!ear)
  75320. return;
  75321. // interlink polygon nodes in z-order
  75322. if (!pass && size)
  75323. indexCurve(ear, minX, minY, size);
  75324. var stop = ear, prev, next;
  75325. // iterate through ears, slicing them one by one
  75326. while (ear.prev !== ear.next) {
  75327. prev = ear.prev;
  75328. next = ear.next;
  75329. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  75330. // cut off the triangle
  75331. triangles.push(prev.i / dim);
  75332. triangles.push(ear.i / dim);
  75333. triangles.push(next.i / dim);
  75334. removeNode(ear);
  75335. // skipping the next vertice leads to less sliver triangles
  75336. ear = next.next;
  75337. stop = next.next;
  75338. continue;
  75339. }
  75340. ear = next;
  75341. // if we looped through the whole remaining polygon and can't find any more ears
  75342. if (ear === stop) {
  75343. // try filtering points and slicing again
  75344. if (!pass) {
  75345. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  75346. // if this didn't work, try curing all small self-intersections locally
  75347. }
  75348. else if (pass === 1) {
  75349. ear = cureLocalIntersections(ear, triangles, dim);
  75350. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  75351. // as a last resort, try splitting the remaining polygon into two
  75352. }
  75353. else if (pass === 2) {
  75354. splitEarcut(ear, triangles, dim, minX, minY, size);
  75355. }
  75356. break;
  75357. }
  75358. }
  75359. }
  75360. // check whether a polygon node forms a valid ear with adjacent nodes
  75361. function isEar(ear) {
  75362. var a = ear.prev, b = ear, c = ear.next;
  75363. if (area(a, b, c) >= 0)
  75364. return false; // reflex, can't be an ear
  75365. // now make sure we don't have other points inside the potential ear
  75366. var p = ear.next.next;
  75367. while (p !== ear.prev) {
  75368. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  75369. area(p.prev, p, p.next) >= 0)
  75370. return false;
  75371. p = p.next;
  75372. }
  75373. return true;
  75374. }
  75375. function isEarHashed(ear, minX, minY, size) {
  75376. var a = ear.prev, b = ear, c = ear.next;
  75377. if (area(a, b, c) >= 0)
  75378. return false; // reflex, can't be an ear
  75379. // triangle bbox; min & max are calculated like this for speed
  75380. var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y);
  75381. // z-order range for the current triangle bbox;
  75382. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  75383. // first look for points inside the triangle in increasing z-order
  75384. var p = ear.nextZ;
  75385. while (p && p.z <= maxZ) {
  75386. if (p !== ear.prev &&
  75387. p !== ear.next &&
  75388. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  75389. area(p.prev, p, p.next) >= 0)
  75390. return false;
  75391. p = p.nextZ;
  75392. }
  75393. // then look for points in decreasing z-order
  75394. p = ear.prevZ;
  75395. while (p && p.z >= minZ) {
  75396. if (p !== ear.prev &&
  75397. p !== ear.next &&
  75398. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  75399. area(p.prev, p, p.next) >= 0)
  75400. return false;
  75401. p = p.prevZ;
  75402. }
  75403. return true;
  75404. }
  75405. // go through all polygon nodes and cure small local self-intersections
  75406. function cureLocalIntersections(start, triangles, dim) {
  75407. var p = start;
  75408. do {
  75409. var a = p.prev, b = p.next.next;
  75410. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  75411. triangles.push(a.i / dim);
  75412. triangles.push(p.i / dim);
  75413. triangles.push(b.i / dim);
  75414. // remove two nodes involved
  75415. removeNode(p);
  75416. removeNode(p.next);
  75417. p = start = b;
  75418. }
  75419. p = p.next;
  75420. } while (p !== start);
  75421. return p;
  75422. }
  75423. // try splitting polygon into two and triangulate them independently
  75424. function splitEarcut(start, triangles, dim, minX, minY, size) {
  75425. // look for a valid diagonal that divides the polygon into two
  75426. var a = start;
  75427. do {
  75428. var b = a.next.next;
  75429. while (b !== a.prev) {
  75430. if (a.i !== b.i && isValidDiagonal(a, b)) {
  75431. // split the polygon in two by the diagonal
  75432. var c = splitPolygon(a, b);
  75433. // filter colinear points around the cuts
  75434. a = filterPoints(a, a.next);
  75435. c = filterPoints(c, c.next);
  75436. // run earcut on each half
  75437. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  75438. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  75439. return;
  75440. }
  75441. b = b.next;
  75442. }
  75443. a = a.next;
  75444. } while (a !== start);
  75445. }
  75446. // link every hole into the outer loop, producing a single-ring polygon without holes
  75447. function eliminateHoles(data, holeIndices, outerNode, dim) {
  75448. var queue = [], i, len, start, end, list;
  75449. for (i = 0, len = holeIndices.length; i < len; i++) {
  75450. start = holeIndices[i] * dim;
  75451. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  75452. list = linkedList(data, start, end, dim, false);
  75453. if (list === list.next)
  75454. list.steiner = true;
  75455. queue.push(getLeftmost(list));
  75456. }
  75457. queue.sort(compareX);
  75458. // process holes from left to right
  75459. for (i = 0; i < queue.length; i++) {
  75460. eliminateHole(queue[i], outerNode);
  75461. outerNode = filterPoints(outerNode, outerNode.next);
  75462. }
  75463. return outerNode;
  75464. }
  75465. function compareX(a, b) {
  75466. return a.x - b.x;
  75467. }
  75468. // find a bridge between vertices that connects hole with an outer ring and and link it
  75469. function eliminateHole(hole, outerNode) {
  75470. outerNode = findHoleBridge(hole, outerNode);
  75471. if (outerNode) {
  75472. var b = splitPolygon(outerNode, hole);
  75473. filterPoints(b, b.next);
  75474. }
  75475. }
  75476. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  75477. function findHoleBridge(hole, outerNode) {
  75478. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  75479. // find a segment intersected by a ray from the hole's leftmost point to the left;
  75480. // segment's endpoint with lesser x will be potential connection point
  75481. do {
  75482. if (hy <= p.y && hy >= p.next.y) {
  75483. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  75484. if (x <= hx && x > qx) {
  75485. qx = x;
  75486. if (x === hx) {
  75487. if (hy === p.y)
  75488. return p;
  75489. if (hy === p.next.y)
  75490. return p.next;
  75491. }
  75492. m = p.x < p.next.x ? p : p.next;
  75493. }
  75494. }
  75495. p = p.next;
  75496. } while (p !== outerNode);
  75497. if (!m)
  75498. return null;
  75499. if (hx === qx)
  75500. return m.prev; // hole touches outer segment; pick lower endpoint
  75501. // look for points inside the triangle of hole point, segment intersection and endpoint;
  75502. // if there are no points found, we have a valid connection;
  75503. // otherwise choose the point of the minimum angle with the ray as connection point
  75504. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  75505. p = m.next;
  75506. while (p !== stop) {
  75507. if (hx >= p.x &&
  75508. p.x >= mx &&
  75509. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  75510. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  75511. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  75512. m = p;
  75513. tanMin = tan;
  75514. }
  75515. }
  75516. p = p.next;
  75517. }
  75518. return m;
  75519. }
  75520. // interlink polygon nodes in z-order
  75521. function indexCurve(start, minX, minY, size) {
  75522. var p = start;
  75523. do {
  75524. if (p.z === null)
  75525. p.z = zOrder(p.x, p.y, minX, minY, size);
  75526. p.prevZ = p.prev;
  75527. p.nextZ = p.next;
  75528. p = p.next;
  75529. } while (p !== start);
  75530. p.prevZ.nextZ = null;
  75531. p.prevZ = null;
  75532. sortLinked(p);
  75533. }
  75534. // Simon Tatham's linked list merge sort algorithm
  75535. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  75536. function sortLinked(list) {
  75537. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  75538. do {
  75539. p = list;
  75540. list = null;
  75541. tail = null;
  75542. numMerges = 0;
  75543. while (p) {
  75544. numMerges++;
  75545. q = p;
  75546. pSize = 0;
  75547. for (i = 0; i < inSize; i++) {
  75548. pSize++;
  75549. q = q.nextZ;
  75550. if (!q)
  75551. break;
  75552. }
  75553. qSize = inSize;
  75554. while (pSize > 0 || (qSize > 0 && q)) {
  75555. if (pSize === 0) {
  75556. e = q;
  75557. q = q.nextZ;
  75558. qSize--;
  75559. }
  75560. else if (qSize === 0 || !q) {
  75561. e = p;
  75562. p = p.nextZ;
  75563. pSize--;
  75564. }
  75565. else if (p.z <= q.z) {
  75566. e = p;
  75567. p = p.nextZ;
  75568. pSize--;
  75569. }
  75570. else {
  75571. e = q;
  75572. q = q.nextZ;
  75573. qSize--;
  75574. }
  75575. if (tail)
  75576. tail.nextZ = e;
  75577. else
  75578. list = e;
  75579. e.prevZ = tail;
  75580. tail = e;
  75581. }
  75582. p = q;
  75583. }
  75584. tail.nextZ = null;
  75585. inSize *= 2;
  75586. } while (numMerges > 1);
  75587. return list;
  75588. }
  75589. // z-order of a point given coords and size of the data bounding box
  75590. function zOrder(x, y, minX, minY, size) {
  75591. // coords are transformed into non-negative 15-bit integer range
  75592. x = 32767 * (x - minX) / size;
  75593. y = 32767 * (y - minY) / size;
  75594. x = (x | (x << 8)) & 0x00FF00FF;
  75595. x = (x | (x << 4)) & 0x0F0F0F0F;
  75596. x = (x | (x << 2)) & 0x33333333;
  75597. x = (x | (x << 1)) & 0x55555555;
  75598. y = (y | (y << 8)) & 0x00FF00FF;
  75599. y = (y | (y << 4)) & 0x0F0F0F0F;
  75600. y = (y | (y << 2)) & 0x33333333;
  75601. y = (y | (y << 1)) & 0x55555555;
  75602. return x | (y << 1);
  75603. }
  75604. // find the leftmost node of a polygon ring
  75605. function getLeftmost(start) {
  75606. var p = start, leftmost = start;
  75607. do {
  75608. if (p.x < leftmost.x)
  75609. leftmost = p;
  75610. p = p.next;
  75611. } while (p !== start);
  75612. return leftmost;
  75613. }
  75614. // check if a point lies within a convex triangle
  75615. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  75616. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  75617. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  75618. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  75619. }
  75620. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  75621. function isValidDiagonal(a, b) {
  75622. return a.next.i !== b.i &&
  75623. a.prev.i !== b.i &&
  75624. !intersectsPolygon(a, b) &&
  75625. locallyInside(a, b) &&
  75626. locallyInside(b, a) &&
  75627. middleInside(a, b);
  75628. }
  75629. // signed area of a triangle
  75630. function area(p, q, r) {
  75631. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  75632. }
  75633. // check if two points are equal
  75634. function equals(p1, p2) {
  75635. return p1.x === p2.x && p1.y === p2.y;
  75636. }
  75637. // check if two segments intersect
  75638. function intersects(p1, q1, p2, q2) {
  75639. if ((equals(p1, q1) && equals(p2, q2)) ||
  75640. (equals(p1, q2) && equals(p2, q1)))
  75641. return true;
  75642. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  75643. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  75644. }
  75645. // check if a polygon diagonal intersects any polygon segments
  75646. function intersectsPolygon(a, b) {
  75647. var p = a;
  75648. do {
  75649. if (p.i !== a.i &&
  75650. p.next.i !== a.i &&
  75651. p.i !== b.i &&
  75652. p.next.i !== b.i &&
  75653. intersects(p, p.next, a, b))
  75654. return true;
  75655. p = p.next;
  75656. } while (p !== a);
  75657. return false;
  75658. }
  75659. // check if a polygon diagonal is locally inside the polygon
  75660. function locallyInside(a, b) {
  75661. return area(a.prev, a, a.next) < 0
  75662. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  75663. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  75664. }
  75665. // check if the middle point of a polygon diagonal is inside the polygon
  75666. function middleInside(a, b) {
  75667. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  75668. do {
  75669. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  75670. inside = !inside;
  75671. p = p.next;
  75672. } while (p !== a);
  75673. return inside;
  75674. }
  75675. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  75676. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  75677. function splitPolygon(a, b) {
  75678. var a2 = new Node(a.i, a.x, a.y), b2 = new Node(b.i, b.x, b.y), an = a.next, bp = b.prev;
  75679. a.next = b;
  75680. b.prev = a;
  75681. a2.next = an;
  75682. an.prev = a2;
  75683. b2.next = a2;
  75684. a2.prev = b2;
  75685. bp.next = b2;
  75686. b2.prev = bp;
  75687. return b2;
  75688. }
  75689. // create a node and optionally link it with previous one (in a circular doubly linked list)
  75690. function insertNode(i, x, y, last) {
  75691. var p = new Node(i, x, y);
  75692. if (!last) {
  75693. p.prev = p;
  75694. p.next = p;
  75695. }
  75696. else {
  75697. p.next = last.next;
  75698. p.prev = last;
  75699. last.next.prev = p;
  75700. last.next = p;
  75701. }
  75702. return p;
  75703. }
  75704. function removeNode(p) {
  75705. p.next.prev = p.prev;
  75706. p.prev.next = p.next;
  75707. if (p.prevZ)
  75708. p.prevZ.nextZ = p.nextZ;
  75709. if (p.nextZ)
  75710. p.nextZ.prevZ = p.prevZ;
  75711. }
  75712. /**
  75713. * return a percentage difference between the polygon area and its triangulation area;
  75714. * used to verify correctness of triangulation
  75715. */
  75716. function deviation(data, holeIndices, dim, triangles) {
  75717. var hasHoles = holeIndices && holeIndices.length;
  75718. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  75719. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  75720. if (hasHoles) {
  75721. for (var i = 0, len = holeIndices.length; i < len; i++) {
  75722. var start = holeIndices[i] * dim;
  75723. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  75724. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  75725. }
  75726. }
  75727. var trianglesArea = 0;
  75728. for (i = 0; i < triangles.length; i += 3) {
  75729. var a = triangles[i] * dim;
  75730. var b = triangles[i + 1] * dim;
  75731. var c = triangles[i + 2] * dim;
  75732. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  75733. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  75734. }
  75735. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  75736. }
  75737. Earcut.deviation = deviation;
  75738. ;
  75739. function signedArea(data, start, end, dim) {
  75740. var sum = 0;
  75741. for (var i = start, j = end - dim; i < end; i += dim) {
  75742. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  75743. j = i;
  75744. }
  75745. return sum;
  75746. }
  75747. /**
  75748. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  75749. */
  75750. function flatten(data) {
  75751. var dim = data[0][0].length, result = { vertices: new Array(), holes: new Array(), dimensions: dim }, holeIndex = 0;
  75752. for (var i = 0; i < data.length; i++) {
  75753. for (var j = 0; j < data[i].length; j++) {
  75754. for (var d = 0; d < dim; d++)
  75755. result.vertices.push(data[i][j][d]);
  75756. }
  75757. if (i > 0) {
  75758. holeIndex += data[i - 1].length;
  75759. result.holes.push(holeIndex);
  75760. }
  75761. }
  75762. return result;
  75763. }
  75764. Earcut.flatten = flatten;
  75765. ;
  75766. })(Earcut || (Earcut = {}));
  75767. //# sourceMappingURL=babylon.earcut.js.map
  75768. "use strict";
  75769. var BABYLON;
  75770. (function (BABYLON) {
  75771. var IndexedVector2 = /** @class */ (function (_super) {
  75772. __extends(IndexedVector2, _super);
  75773. function IndexedVector2(original, index) {
  75774. var _this = _super.call(this, original.x, original.y) || this;
  75775. _this.index = index;
  75776. return _this;
  75777. }
  75778. return IndexedVector2;
  75779. }(BABYLON.Vector2));
  75780. var PolygonPoints = /** @class */ (function () {
  75781. function PolygonPoints() {
  75782. this.elements = new Array();
  75783. }
  75784. PolygonPoints.prototype.add = function (originalPoints) {
  75785. var _this = this;
  75786. var result = new Array();
  75787. originalPoints.forEach(function (point) {
  75788. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  75789. var newPoint = new IndexedVector2(point, _this.elements.length);
  75790. result.push(newPoint);
  75791. _this.elements.push(newPoint);
  75792. }
  75793. });
  75794. return result;
  75795. };
  75796. PolygonPoints.prototype.computeBounds = function () {
  75797. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  75798. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  75799. this.elements.forEach(function (point) {
  75800. // x
  75801. if (point.x < lmin.x) {
  75802. lmin.x = point.x;
  75803. }
  75804. else if (point.x > lmax.x) {
  75805. lmax.x = point.x;
  75806. }
  75807. // y
  75808. if (point.y < lmin.y) {
  75809. lmin.y = point.y;
  75810. }
  75811. else if (point.y > lmax.y) {
  75812. lmax.y = point.y;
  75813. }
  75814. });
  75815. return {
  75816. min: lmin,
  75817. max: lmax,
  75818. width: lmax.x - lmin.x,
  75819. height: lmax.y - lmin.y
  75820. };
  75821. };
  75822. return PolygonPoints;
  75823. }());
  75824. var Polygon = /** @class */ (function () {
  75825. function Polygon() {
  75826. }
  75827. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  75828. return [
  75829. new BABYLON.Vector2(xmin, ymin),
  75830. new BABYLON.Vector2(xmax, ymin),
  75831. new BABYLON.Vector2(xmax, ymax),
  75832. new BABYLON.Vector2(xmin, ymax)
  75833. ];
  75834. };
  75835. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  75836. if (cx === void 0) { cx = 0; }
  75837. if (cy === void 0) { cy = 0; }
  75838. if (numberOfSides === void 0) { numberOfSides = 32; }
  75839. var result = new Array();
  75840. var angle = 0;
  75841. var increment = (Math.PI * 2) / numberOfSides;
  75842. for (var i = 0; i < numberOfSides; i++) {
  75843. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  75844. angle -= increment;
  75845. }
  75846. return result;
  75847. };
  75848. Polygon.Parse = function (input) {
  75849. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  75850. var i, result = [];
  75851. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  75852. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  75853. }
  75854. return result;
  75855. };
  75856. Polygon.StartingAt = function (x, y) {
  75857. return BABYLON.Path2.StartingAt(x, y);
  75858. };
  75859. return Polygon;
  75860. }());
  75861. BABYLON.Polygon = Polygon;
  75862. var PolygonMeshBuilder = /** @class */ (function () {
  75863. function PolygonMeshBuilder(name, contours, scene) {
  75864. this._points = new PolygonPoints();
  75865. this._outlinepoints = new PolygonPoints();
  75866. this._holes = new Array();
  75867. this._epoints = new Array();
  75868. this._eholes = new Array();
  75869. this._name = name;
  75870. this._scene = scene;
  75871. var points;
  75872. if (contours instanceof BABYLON.Path2) {
  75873. points = contours.getPoints();
  75874. }
  75875. else {
  75876. points = contours;
  75877. }
  75878. this._addToepoint(points);
  75879. this._points.add(points);
  75880. this._outlinepoints.add(points);
  75881. }
  75882. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  75883. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  75884. var p = points_1[_i];
  75885. this._epoints.push(p.x, p.y);
  75886. }
  75887. };
  75888. PolygonMeshBuilder.prototype.addHole = function (hole) {
  75889. this._points.add(hole);
  75890. var holepoints = new PolygonPoints();
  75891. holepoints.add(hole);
  75892. this._holes.push(holepoints);
  75893. this._eholes.push(this._epoints.length / 2);
  75894. this._addToepoint(hole);
  75895. return this;
  75896. };
  75897. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  75898. var _this = this;
  75899. if (updatable === void 0) { updatable = false; }
  75900. if (depth === void 0) { depth = 0; }
  75901. var result = new BABYLON.Mesh(this._name, this._scene);
  75902. var normals = new Array();
  75903. var positions = new Array();
  75904. var uvs = new Array();
  75905. var bounds = this._points.computeBounds();
  75906. this._points.elements.forEach(function (p) {
  75907. normals.push(0, 1.0, 0);
  75908. positions.push(p.x, 0, p.y);
  75909. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  75910. });
  75911. var indices = new Array();
  75912. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  75913. for (var i = 0; i < res.length; i++) {
  75914. indices.push(res[i]);
  75915. }
  75916. if (depth > 0) {
  75917. var positionscount = (positions.length / 3); //get the current pointcount
  75918. this._points.elements.forEach(function (p) {
  75919. normals.push(0, -1.0, 0);
  75920. positions.push(p.x, -depth, p.y);
  75921. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  75922. });
  75923. var totalCount = indices.length;
  75924. for (var i = 0; i < totalCount; i += 3) {
  75925. var i0 = indices[i + 0];
  75926. var i1 = indices[i + 1];
  75927. var i2 = indices[i + 2];
  75928. indices.push(i2 + positionscount);
  75929. indices.push(i1 + positionscount);
  75930. indices.push(i0 + positionscount);
  75931. }
  75932. //Add the sides
  75933. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  75934. this._holes.forEach(function (hole) {
  75935. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  75936. });
  75937. }
  75938. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  75939. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  75940. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  75941. result.setIndices(indices);
  75942. return result;
  75943. };
  75944. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  75945. var StartIndex = positions.length / 3;
  75946. var ulength = 0;
  75947. for (var i = 0; i < points.elements.length; i++) {
  75948. var p = points.elements[i];
  75949. var p1;
  75950. if ((i + 1) > points.elements.length - 1) {
  75951. p1 = points.elements[0];
  75952. }
  75953. else {
  75954. p1 = points.elements[i + 1];
  75955. }
  75956. positions.push(p.x, 0, p.y);
  75957. positions.push(p.x, -depth, p.y);
  75958. positions.push(p1.x, 0, p1.y);
  75959. positions.push(p1.x, -depth, p1.y);
  75960. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  75961. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  75962. var v3 = v2.subtract(v1);
  75963. var v4 = new BABYLON.Vector3(0, 1, 0);
  75964. var vn = BABYLON.Vector3.Cross(v3, v4);
  75965. vn = vn.normalize();
  75966. uvs.push(ulength / bounds.width, 0);
  75967. uvs.push(ulength / bounds.width, 1);
  75968. ulength += v3.length();
  75969. uvs.push((ulength / bounds.width), 0);
  75970. uvs.push((ulength / bounds.width), 1);
  75971. if (!flip) {
  75972. normals.push(-vn.x, -vn.y, -vn.z);
  75973. normals.push(-vn.x, -vn.y, -vn.z);
  75974. normals.push(-vn.x, -vn.y, -vn.z);
  75975. normals.push(-vn.x, -vn.y, -vn.z);
  75976. indices.push(StartIndex);
  75977. indices.push(StartIndex + 1);
  75978. indices.push(StartIndex + 2);
  75979. indices.push(StartIndex + 1);
  75980. indices.push(StartIndex + 3);
  75981. indices.push(StartIndex + 2);
  75982. }
  75983. else {
  75984. normals.push(vn.x, vn.y, vn.z);
  75985. normals.push(vn.x, vn.y, vn.z);
  75986. normals.push(vn.x, vn.y, vn.z);
  75987. normals.push(vn.x, vn.y, vn.z);
  75988. indices.push(StartIndex);
  75989. indices.push(StartIndex + 2);
  75990. indices.push(StartIndex + 1);
  75991. indices.push(StartIndex + 1);
  75992. indices.push(StartIndex + 2);
  75993. indices.push(StartIndex + 3);
  75994. }
  75995. StartIndex += 4;
  75996. }
  75997. ;
  75998. };
  75999. return PolygonMeshBuilder;
  76000. }());
  76001. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  76002. })(BABYLON || (BABYLON = {}));
  76003. //# sourceMappingURL=babylon.polygonMesh.js.map
  76004. "use strict";
  76005. var BABYLON;
  76006. (function (BABYLON) {
  76007. // Unique ID when we import meshes from Babylon to CSG
  76008. var currentCSGMeshId = 0;
  76009. // # class Vertex
  76010. // Represents a vertex of a polygon. Use your own vertex class instead of this
  76011. // one to provide additional features like texture coordinates and vertex
  76012. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  76013. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  76014. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  76015. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  76016. // is not used anywhere else.
  76017. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  76018. var Vertex = /** @class */ (function () {
  76019. function Vertex(pos, normal, uv) {
  76020. this.pos = pos;
  76021. this.normal = normal;
  76022. this.uv = uv;
  76023. }
  76024. Vertex.prototype.clone = function () {
  76025. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  76026. };
  76027. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  76028. // orientation of a polygon is flipped.
  76029. Vertex.prototype.flip = function () {
  76030. this.normal = this.normal.scale(-1);
  76031. };
  76032. // Create a new vertex between this vertex and `other` by linearly
  76033. // interpolating all properties using a parameter of `t`. Subclasses should
  76034. // override this to interpolate additional properties.
  76035. Vertex.prototype.interpolate = function (other, t) {
  76036. 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));
  76037. };
  76038. return Vertex;
  76039. }());
  76040. // # class Plane
  76041. // Represents a plane in 3D space.
  76042. var Plane = /** @class */ (function () {
  76043. function Plane(normal, w) {
  76044. this.normal = normal;
  76045. this.w = w;
  76046. }
  76047. Plane.FromPoints = function (a, b, c) {
  76048. var v0 = c.subtract(a);
  76049. var v1 = b.subtract(a);
  76050. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  76051. return null;
  76052. }
  76053. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  76054. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  76055. };
  76056. Plane.prototype.clone = function () {
  76057. return new Plane(this.normal.clone(), this.w);
  76058. };
  76059. Plane.prototype.flip = function () {
  76060. this.normal.scaleInPlace(-1);
  76061. this.w = -this.w;
  76062. };
  76063. // Split `polygon` by this plane if needed, then put the polygon or polygon
  76064. // fragments in the appropriate lists. Coplanar polygons go into either
  76065. // `coplanarFront` or `coplanarBack` depending on their orientation with
  76066. // respect to this plane. Polygons in front or in back of this plane go into
  76067. // either `front` or `back`.
  76068. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  76069. var COPLANAR = 0;
  76070. var FRONT = 1;
  76071. var BACK = 2;
  76072. var SPANNING = 3;
  76073. // Classify each point as well as the entire polygon into one of the above
  76074. // four classes.
  76075. var polygonType = 0;
  76076. var types = [];
  76077. var i;
  76078. var t;
  76079. for (i = 0; i < polygon.vertices.length; i++) {
  76080. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  76081. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  76082. polygonType |= type;
  76083. types.push(type);
  76084. }
  76085. // Put the polygon in the correct list, splitting it when necessary.
  76086. switch (polygonType) {
  76087. case COPLANAR:
  76088. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  76089. break;
  76090. case FRONT:
  76091. front.push(polygon);
  76092. break;
  76093. case BACK:
  76094. back.push(polygon);
  76095. break;
  76096. case SPANNING:
  76097. var f = [], b = [];
  76098. for (i = 0; i < polygon.vertices.length; i++) {
  76099. var j = (i + 1) % polygon.vertices.length;
  76100. var ti = types[i], tj = types[j];
  76101. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  76102. if (ti !== BACK)
  76103. f.push(vi);
  76104. if (ti !== FRONT)
  76105. b.push(ti !== BACK ? vi.clone() : vi);
  76106. if ((ti | tj) === SPANNING) {
  76107. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  76108. var v = vi.interpolate(vj, t);
  76109. f.push(v);
  76110. b.push(v.clone());
  76111. }
  76112. }
  76113. var poly;
  76114. if (f.length >= 3) {
  76115. poly = new Polygon(f, polygon.shared);
  76116. if (poly.plane)
  76117. front.push(poly);
  76118. }
  76119. if (b.length >= 3) {
  76120. poly = new Polygon(b, polygon.shared);
  76121. if (poly.plane)
  76122. back.push(poly);
  76123. }
  76124. break;
  76125. }
  76126. };
  76127. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  76128. // point is on the plane.
  76129. Plane.EPSILON = 1e-5;
  76130. return Plane;
  76131. }());
  76132. // # class Polygon
  76133. // Represents a convex polygon. The vertices used to initialize a polygon must
  76134. // be coplanar and form a convex loop.
  76135. //
  76136. // Each convex polygon has a `shared` property, which is shared between all
  76137. // polygons that are clones of each other or were split from the same polygon.
  76138. // This can be used to define per-polygon properties (such as surface color).
  76139. var Polygon = /** @class */ (function () {
  76140. function Polygon(vertices, shared) {
  76141. this.vertices = vertices;
  76142. this.shared = shared;
  76143. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  76144. }
  76145. Polygon.prototype.clone = function () {
  76146. var vertices = this.vertices.map(function (v) { return v.clone(); });
  76147. return new Polygon(vertices, this.shared);
  76148. };
  76149. Polygon.prototype.flip = function () {
  76150. this.vertices.reverse().map(function (v) { v.flip(); });
  76151. this.plane.flip();
  76152. };
  76153. return Polygon;
  76154. }());
  76155. // # class Node
  76156. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  76157. // by picking a polygon to split along. That polygon (and all other coplanar
  76158. // polygons) are added directly to that node and the other polygons are added to
  76159. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  76160. // no distinction between internal and leaf nodes.
  76161. var Node = /** @class */ (function () {
  76162. function Node(polygons) {
  76163. this.plane = null;
  76164. this.front = null;
  76165. this.back = null;
  76166. this.polygons = new Array();
  76167. if (polygons) {
  76168. this.build(polygons);
  76169. }
  76170. }
  76171. Node.prototype.clone = function () {
  76172. var node = new Node();
  76173. node.plane = this.plane && this.plane.clone();
  76174. node.front = this.front && this.front.clone();
  76175. node.back = this.back && this.back.clone();
  76176. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  76177. return node;
  76178. };
  76179. // Convert solid space to empty space and empty space to solid space.
  76180. Node.prototype.invert = function () {
  76181. for (var i = 0; i < this.polygons.length; i++) {
  76182. this.polygons[i].flip();
  76183. }
  76184. if (this.plane) {
  76185. this.plane.flip();
  76186. }
  76187. if (this.front) {
  76188. this.front.invert();
  76189. }
  76190. if (this.back) {
  76191. this.back.invert();
  76192. }
  76193. var temp = this.front;
  76194. this.front = this.back;
  76195. this.back = temp;
  76196. };
  76197. // Recursively remove all polygons in `polygons` that are inside this BSP
  76198. // tree.
  76199. Node.prototype.clipPolygons = function (polygons) {
  76200. if (!this.plane)
  76201. return polygons.slice();
  76202. var front = new Array(), back = new Array();
  76203. for (var i = 0; i < polygons.length; i++) {
  76204. this.plane.splitPolygon(polygons[i], front, back, front, back);
  76205. }
  76206. if (this.front) {
  76207. front = this.front.clipPolygons(front);
  76208. }
  76209. if (this.back) {
  76210. back = this.back.clipPolygons(back);
  76211. }
  76212. else {
  76213. back = [];
  76214. }
  76215. return front.concat(back);
  76216. };
  76217. // Remove all polygons in this BSP tree that are inside the other BSP tree
  76218. // `bsp`.
  76219. Node.prototype.clipTo = function (bsp) {
  76220. this.polygons = bsp.clipPolygons(this.polygons);
  76221. if (this.front)
  76222. this.front.clipTo(bsp);
  76223. if (this.back)
  76224. this.back.clipTo(bsp);
  76225. };
  76226. // Return a list of all polygons in this BSP tree.
  76227. Node.prototype.allPolygons = function () {
  76228. var polygons = this.polygons.slice();
  76229. if (this.front)
  76230. polygons = polygons.concat(this.front.allPolygons());
  76231. if (this.back)
  76232. polygons = polygons.concat(this.back.allPolygons());
  76233. return polygons;
  76234. };
  76235. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  76236. // new polygons are filtered down to the bottom of the tree and become new
  76237. // nodes there. Each set of polygons is partitioned using the first polygon
  76238. // (no heuristic is used to pick a good split).
  76239. Node.prototype.build = function (polygons) {
  76240. if (!polygons.length)
  76241. return;
  76242. if (!this.plane)
  76243. this.plane = polygons[0].plane.clone();
  76244. var front = new Array(), back = new Array();
  76245. for (var i = 0; i < polygons.length; i++) {
  76246. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  76247. }
  76248. if (front.length) {
  76249. if (!this.front)
  76250. this.front = new Node();
  76251. this.front.build(front);
  76252. }
  76253. if (back.length) {
  76254. if (!this.back)
  76255. this.back = new Node();
  76256. this.back.build(back);
  76257. }
  76258. };
  76259. return Node;
  76260. }());
  76261. var CSG = /** @class */ (function () {
  76262. function CSG() {
  76263. this.polygons = new Array();
  76264. }
  76265. // Convert BABYLON.Mesh to BABYLON.CSG
  76266. CSG.FromMesh = function (mesh) {
  76267. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  76268. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  76269. if (mesh instanceof BABYLON.Mesh) {
  76270. mesh.computeWorldMatrix(true);
  76271. matrix = mesh.getWorldMatrix();
  76272. meshPosition = mesh.position.clone();
  76273. meshRotation = mesh.rotation.clone();
  76274. if (mesh.rotationQuaternion) {
  76275. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  76276. }
  76277. meshScaling = mesh.scaling.clone();
  76278. }
  76279. else {
  76280. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  76281. }
  76282. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  76283. var subMeshes = mesh.subMeshes;
  76284. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  76285. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  76286. vertices = [];
  76287. for (var j = 0; j < 3; j++) {
  76288. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  76289. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  76290. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  76291. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  76292. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  76293. vertex = new Vertex(position, normal, uv);
  76294. vertices.push(vertex);
  76295. }
  76296. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  76297. // To handle the case of degenerated triangle
  76298. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  76299. if (polygon.plane)
  76300. polygons.push(polygon);
  76301. }
  76302. }
  76303. var csg = CSG.FromPolygons(polygons);
  76304. csg.matrix = matrix;
  76305. csg.position = meshPosition;
  76306. csg.rotation = meshRotation;
  76307. csg.scaling = meshScaling;
  76308. csg.rotationQuaternion = meshRotationQuaternion;
  76309. currentCSGMeshId++;
  76310. return csg;
  76311. };
  76312. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  76313. CSG.FromPolygons = function (polygons) {
  76314. var csg = new CSG();
  76315. csg.polygons = polygons;
  76316. return csg;
  76317. };
  76318. CSG.prototype.clone = function () {
  76319. var csg = new CSG();
  76320. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  76321. csg.copyTransformAttributes(this);
  76322. return csg;
  76323. };
  76324. CSG.prototype.union = function (csg) {
  76325. var a = new Node(this.clone().polygons);
  76326. var b = new Node(csg.clone().polygons);
  76327. a.clipTo(b);
  76328. b.clipTo(a);
  76329. b.invert();
  76330. b.clipTo(a);
  76331. b.invert();
  76332. a.build(b.allPolygons());
  76333. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  76334. };
  76335. CSG.prototype.unionInPlace = function (csg) {
  76336. var a = new Node(this.polygons);
  76337. var b = new Node(csg.polygons);
  76338. a.clipTo(b);
  76339. b.clipTo(a);
  76340. b.invert();
  76341. b.clipTo(a);
  76342. b.invert();
  76343. a.build(b.allPolygons());
  76344. this.polygons = a.allPolygons();
  76345. };
  76346. CSG.prototype.subtract = function (csg) {
  76347. var a = new Node(this.clone().polygons);
  76348. var b = new Node(csg.clone().polygons);
  76349. a.invert();
  76350. a.clipTo(b);
  76351. b.clipTo(a);
  76352. b.invert();
  76353. b.clipTo(a);
  76354. b.invert();
  76355. a.build(b.allPolygons());
  76356. a.invert();
  76357. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  76358. };
  76359. CSG.prototype.subtractInPlace = function (csg) {
  76360. var a = new Node(this.polygons);
  76361. var b = new Node(csg.polygons);
  76362. a.invert();
  76363. a.clipTo(b);
  76364. b.clipTo(a);
  76365. b.invert();
  76366. b.clipTo(a);
  76367. b.invert();
  76368. a.build(b.allPolygons());
  76369. a.invert();
  76370. this.polygons = a.allPolygons();
  76371. };
  76372. CSG.prototype.intersect = function (csg) {
  76373. var a = new Node(this.clone().polygons);
  76374. var b = new Node(csg.clone().polygons);
  76375. a.invert();
  76376. b.clipTo(a);
  76377. b.invert();
  76378. a.clipTo(b);
  76379. b.clipTo(a);
  76380. a.build(b.allPolygons());
  76381. a.invert();
  76382. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  76383. };
  76384. CSG.prototype.intersectInPlace = function (csg) {
  76385. var a = new Node(this.polygons);
  76386. var b = new Node(csg.polygons);
  76387. a.invert();
  76388. b.clipTo(a);
  76389. b.invert();
  76390. a.clipTo(b);
  76391. b.clipTo(a);
  76392. a.build(b.allPolygons());
  76393. a.invert();
  76394. this.polygons = a.allPolygons();
  76395. };
  76396. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  76397. // not modified.
  76398. CSG.prototype.inverse = function () {
  76399. var csg = this.clone();
  76400. csg.inverseInPlace();
  76401. return csg;
  76402. };
  76403. CSG.prototype.inverseInPlace = function () {
  76404. this.polygons.map(function (p) { p.flip(); });
  76405. };
  76406. // This is used to keep meshes transformations so they can be restored
  76407. // when we build back a Babylon Mesh
  76408. // NB : All CSG operations are performed in world coordinates
  76409. CSG.prototype.copyTransformAttributes = function (csg) {
  76410. this.matrix = csg.matrix;
  76411. this.position = csg.position;
  76412. this.rotation = csg.rotation;
  76413. this.scaling = csg.scaling;
  76414. this.rotationQuaternion = csg.rotationQuaternion;
  76415. return this;
  76416. };
  76417. // Build Raw mesh from CSG
  76418. // Coordinates here are in world space
  76419. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  76420. var matrix = this.matrix.clone();
  76421. matrix.invert();
  76422. 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;
  76423. if (keepSubMeshes) {
  76424. // Sort Polygons, since subMeshes are indices range
  76425. polygons.sort(function (a, b) {
  76426. if (a.shared.meshId === b.shared.meshId) {
  76427. return a.shared.subMeshId - b.shared.subMeshId;
  76428. }
  76429. else {
  76430. return a.shared.meshId - b.shared.meshId;
  76431. }
  76432. });
  76433. }
  76434. for (var i = 0, il = polygons.length; i < il; i++) {
  76435. polygon = polygons[i];
  76436. // Building SubMeshes
  76437. if (!subMesh_dict[polygon.shared.meshId]) {
  76438. subMesh_dict[polygon.shared.meshId] = {};
  76439. }
  76440. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  76441. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  76442. indexStart: +Infinity,
  76443. indexEnd: -Infinity,
  76444. materialIndex: polygon.shared.materialIndex
  76445. };
  76446. }
  76447. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  76448. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  76449. polygonIndices[0] = 0;
  76450. polygonIndices[1] = j - 1;
  76451. polygonIndices[2] = j;
  76452. for (var k = 0; k < 3; k++) {
  76453. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  76454. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  76455. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  76456. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  76457. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  76458. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  76459. // Check if 2 points can be merged
  76460. if (!(typeof vertex_idx !== 'undefined' &&
  76461. normals[vertex_idx * 3] === localNormal.x &&
  76462. normals[vertex_idx * 3 + 1] === localNormal.y &&
  76463. normals[vertex_idx * 3 + 2] === localNormal.z &&
  76464. uvs[vertex_idx * 2] === uv.x &&
  76465. uvs[vertex_idx * 2 + 1] === uv.y)) {
  76466. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  76467. uvs.push(uv.x, uv.y);
  76468. normals.push(normal.x, normal.y, normal.z);
  76469. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  76470. }
  76471. indices.push(vertex_idx);
  76472. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  76473. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  76474. currentIndex++;
  76475. }
  76476. }
  76477. }
  76478. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  76479. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  76480. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  76481. mesh.setIndices(indices, null);
  76482. if (keepSubMeshes) {
  76483. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  76484. var materialIndexOffset = 0, materialMaxIndex;
  76485. mesh.subMeshes = new Array();
  76486. for (var m in subMesh_dict) {
  76487. materialMaxIndex = -1;
  76488. for (var sm in subMesh_dict[m]) {
  76489. subMesh_obj = subMesh_dict[m][sm];
  76490. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  76491. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  76492. }
  76493. materialIndexOffset += ++materialMaxIndex;
  76494. }
  76495. }
  76496. return mesh;
  76497. };
  76498. // Build Mesh from CSG taking material and transforms into account
  76499. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  76500. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  76501. mesh.material = material;
  76502. mesh.position.copyFrom(this.position);
  76503. mesh.rotation.copyFrom(this.rotation);
  76504. if (this.rotationQuaternion) {
  76505. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  76506. }
  76507. mesh.scaling.copyFrom(this.scaling);
  76508. mesh.computeWorldMatrix(true);
  76509. return mesh;
  76510. };
  76511. return CSG;
  76512. }());
  76513. BABYLON.CSG = CSG;
  76514. })(BABYLON || (BABYLON = {}));
  76515. //# sourceMappingURL=babylon.csg.js.map
  76516. "use strict";
  76517. var BABYLON;
  76518. (function (BABYLON) {
  76519. var LensFlare = /** @class */ (function () {
  76520. function LensFlare(size, position, color, imgUrl, system) {
  76521. this.size = size;
  76522. this.position = position;
  76523. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  76524. this.color = color || new BABYLON.Color3(1, 1, 1);
  76525. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  76526. this._system = system;
  76527. system.lensFlares.push(this);
  76528. }
  76529. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  76530. return new LensFlare(size, position, color, imgUrl, system);
  76531. };
  76532. LensFlare.prototype.dispose = function () {
  76533. if (this.texture) {
  76534. this.texture.dispose();
  76535. }
  76536. // Remove from scene
  76537. var index = this._system.lensFlares.indexOf(this);
  76538. this._system.lensFlares.splice(index, 1);
  76539. };
  76540. ;
  76541. return LensFlare;
  76542. }());
  76543. BABYLON.LensFlare = LensFlare;
  76544. })(BABYLON || (BABYLON = {}));
  76545. //# sourceMappingURL=babylon.lensFlare.js.map
  76546. "use strict";
  76547. var BABYLON;
  76548. (function (BABYLON) {
  76549. var LensFlareSystem = /** @class */ (function () {
  76550. function LensFlareSystem(name, emitter, scene) {
  76551. this.name = name;
  76552. this.lensFlares = new Array();
  76553. this.borderLimit = 300;
  76554. this.viewportBorder = 0;
  76555. this.layerMask = 0x0FFFFFFF;
  76556. this._vertexBuffers = {};
  76557. this._isEnabled = true;
  76558. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  76559. this._emitter = emitter;
  76560. this.id = name;
  76561. scene.lensFlareSystems.push(this);
  76562. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  76563. var engine = scene.getEngine();
  76564. // VBO
  76565. var vertices = [];
  76566. vertices.push(1, 1);
  76567. vertices.push(-1, 1);
  76568. vertices.push(-1, -1);
  76569. vertices.push(1, -1);
  76570. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  76571. // Indices
  76572. var indices = [];
  76573. indices.push(0);
  76574. indices.push(1);
  76575. indices.push(2);
  76576. indices.push(0);
  76577. indices.push(2);
  76578. indices.push(3);
  76579. this._indexBuffer = engine.createIndexBuffer(indices);
  76580. // Effects
  76581. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  76582. }
  76583. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  76584. get: function () {
  76585. return this._isEnabled;
  76586. },
  76587. set: function (value) {
  76588. this._isEnabled = value;
  76589. },
  76590. enumerable: true,
  76591. configurable: true
  76592. });
  76593. LensFlareSystem.prototype.getScene = function () {
  76594. return this._scene;
  76595. };
  76596. LensFlareSystem.prototype.getEmitter = function () {
  76597. return this._emitter;
  76598. };
  76599. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  76600. this._emitter = newEmitter;
  76601. };
  76602. LensFlareSystem.prototype.getEmitterPosition = function () {
  76603. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  76604. };
  76605. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  76606. var position = this.getEmitterPosition();
  76607. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  76608. this._positionX = position.x;
  76609. this._positionY = position.y;
  76610. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  76611. if (this.viewportBorder > 0) {
  76612. globalViewport.x -= this.viewportBorder;
  76613. globalViewport.y -= this.viewportBorder;
  76614. globalViewport.width += this.viewportBorder * 2;
  76615. globalViewport.height += this.viewportBorder * 2;
  76616. position.x += this.viewportBorder;
  76617. position.y += this.viewportBorder;
  76618. this._positionX += this.viewportBorder;
  76619. this._positionY += this.viewportBorder;
  76620. }
  76621. if (position.z > 0) {
  76622. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  76623. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  76624. return true;
  76625. }
  76626. return true;
  76627. }
  76628. return false;
  76629. };
  76630. LensFlareSystem.prototype._isVisible = function () {
  76631. if (!this._isEnabled || !this._scene.activeCamera) {
  76632. return false;
  76633. }
  76634. var emitterPosition = this.getEmitterPosition();
  76635. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  76636. var distance = direction.length();
  76637. direction.normalize();
  76638. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  76639. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  76640. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  76641. };
  76642. LensFlareSystem.prototype.render = function () {
  76643. if (!this._effect.isReady() || !this._scene.activeCamera)
  76644. return false;
  76645. var engine = this._scene.getEngine();
  76646. var viewport = this._scene.activeCamera.viewport;
  76647. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  76648. // Position
  76649. if (!this.computeEffectivePosition(globalViewport)) {
  76650. return false;
  76651. }
  76652. // Visibility
  76653. if (!this._isVisible()) {
  76654. return false;
  76655. }
  76656. // Intensity
  76657. var awayX;
  76658. var awayY;
  76659. if (this._positionX < this.borderLimit + globalViewport.x) {
  76660. awayX = this.borderLimit + globalViewport.x - this._positionX;
  76661. }
  76662. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  76663. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  76664. }
  76665. else {
  76666. awayX = 0;
  76667. }
  76668. if (this._positionY < this.borderLimit + globalViewport.y) {
  76669. awayY = this.borderLimit + globalViewport.y - this._positionY;
  76670. }
  76671. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  76672. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  76673. }
  76674. else {
  76675. awayY = 0;
  76676. }
  76677. var away = (awayX > awayY) ? awayX : awayY;
  76678. away -= this.viewportBorder;
  76679. if (away > this.borderLimit) {
  76680. away = this.borderLimit;
  76681. }
  76682. var intensity = 1.0 - (away / this.borderLimit);
  76683. if (intensity < 0) {
  76684. return false;
  76685. }
  76686. if (intensity > 1.0) {
  76687. intensity = 1.0;
  76688. }
  76689. if (this.viewportBorder > 0) {
  76690. globalViewport.x += this.viewportBorder;
  76691. globalViewport.y += this.viewportBorder;
  76692. globalViewport.width -= this.viewportBorder * 2;
  76693. globalViewport.height -= this.viewportBorder * 2;
  76694. this._positionX -= this.viewportBorder;
  76695. this._positionY -= this.viewportBorder;
  76696. }
  76697. // Position
  76698. var centerX = globalViewport.x + globalViewport.width / 2;
  76699. var centerY = globalViewport.y + globalViewport.height / 2;
  76700. var distX = centerX - this._positionX;
  76701. var distY = centerY - this._positionY;
  76702. // Effects
  76703. engine.enableEffect(this._effect);
  76704. engine.setState(false);
  76705. engine.setDepthBuffer(false);
  76706. // VBOs
  76707. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  76708. // Flares
  76709. for (var index = 0; index < this.lensFlares.length; index++) {
  76710. var flare = this.lensFlares[index];
  76711. engine.setAlphaMode(flare.alphaMode);
  76712. var x = centerX - (distX * flare.position);
  76713. var y = centerY - (distY * flare.position);
  76714. var cw = flare.size;
  76715. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  76716. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  76717. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  76718. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  76719. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  76720. // Texture
  76721. this._effect.setTexture("textureSampler", flare.texture);
  76722. // Color
  76723. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  76724. // Draw order
  76725. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  76726. }
  76727. engine.setDepthBuffer(true);
  76728. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  76729. return true;
  76730. };
  76731. LensFlareSystem.prototype.dispose = function () {
  76732. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  76733. if (vertexBuffer) {
  76734. vertexBuffer.dispose();
  76735. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  76736. }
  76737. if (this._indexBuffer) {
  76738. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  76739. this._indexBuffer = null;
  76740. }
  76741. while (this.lensFlares.length) {
  76742. this.lensFlares[0].dispose();
  76743. }
  76744. // Remove from scene
  76745. var index = this._scene.lensFlareSystems.indexOf(this);
  76746. this._scene.lensFlareSystems.splice(index, 1);
  76747. };
  76748. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  76749. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  76750. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  76751. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  76752. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  76753. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  76754. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  76755. var parsedFlare = parsedLensFlareSystem.flares[index];
  76756. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  76757. }
  76758. return lensFlareSystem;
  76759. };
  76760. LensFlareSystem.prototype.serialize = function () {
  76761. var serializationObject = {};
  76762. serializationObject.id = this.id;
  76763. serializationObject.name = this.name;
  76764. serializationObject.emitterId = this.getEmitter().id;
  76765. serializationObject.borderLimit = this.borderLimit;
  76766. serializationObject.flares = [];
  76767. for (var index = 0; index < this.lensFlares.length; index++) {
  76768. var flare = this.lensFlares[index];
  76769. serializationObject.flares.push({
  76770. size: flare.size,
  76771. position: flare.position,
  76772. color: flare.color.asArray(),
  76773. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  76774. });
  76775. }
  76776. return serializationObject;
  76777. };
  76778. return LensFlareSystem;
  76779. }());
  76780. BABYLON.LensFlareSystem = LensFlareSystem;
  76781. })(BABYLON || (BABYLON = {}));
  76782. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  76783. "use strict";
  76784. var BABYLON;
  76785. (function (BABYLON) {
  76786. /**
  76787. * This is a holder class for the physics joint created by the physics plugin.
  76788. * It holds a set of functions to control the underlying joint.
  76789. */
  76790. var PhysicsJoint = /** @class */ (function () {
  76791. function PhysicsJoint(type, jointData) {
  76792. this.type = type;
  76793. this.jointData = jointData;
  76794. jointData.nativeParams = jointData.nativeParams || {};
  76795. }
  76796. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  76797. get: function () {
  76798. return this._physicsJoint;
  76799. },
  76800. set: function (newJoint) {
  76801. if (this._physicsJoint) {
  76802. //remove from the wolrd
  76803. }
  76804. this._physicsJoint = newJoint;
  76805. },
  76806. enumerable: true,
  76807. configurable: true
  76808. });
  76809. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  76810. set: function (physicsPlugin) {
  76811. this._physicsPlugin = physicsPlugin;
  76812. },
  76813. enumerable: true,
  76814. configurable: true
  76815. });
  76816. /**
  76817. * Execute a function that is physics-plugin specific.
  76818. * @param {Function} func the function that will be executed.
  76819. * It accepts two parameters: the physics world and the physics joint.
  76820. */
  76821. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  76822. func(this._physicsPlugin.world, this._physicsJoint);
  76823. };
  76824. //TODO check if the native joints are the same
  76825. //Joint Types
  76826. PhysicsJoint.DistanceJoint = 0;
  76827. PhysicsJoint.HingeJoint = 1;
  76828. PhysicsJoint.BallAndSocketJoint = 2;
  76829. PhysicsJoint.WheelJoint = 3;
  76830. PhysicsJoint.SliderJoint = 4;
  76831. //OIMO
  76832. PhysicsJoint.PrismaticJoint = 5;
  76833. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  76834. PhysicsJoint.UniversalJoint = 6;
  76835. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  76836. //Cannon
  76837. //Similar to a Ball-Joint. Different in params
  76838. PhysicsJoint.PointToPointJoint = 8;
  76839. //Cannon only at the moment
  76840. PhysicsJoint.SpringJoint = 9;
  76841. PhysicsJoint.LockJoint = 10;
  76842. return PhysicsJoint;
  76843. }());
  76844. BABYLON.PhysicsJoint = PhysicsJoint;
  76845. /**
  76846. * A class representing a physics distance joint.
  76847. */
  76848. var DistanceJoint = /** @class */ (function (_super) {
  76849. __extends(DistanceJoint, _super);
  76850. function DistanceJoint(jointData) {
  76851. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  76852. }
  76853. /**
  76854. * Update the predefined distance.
  76855. */
  76856. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  76857. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  76858. };
  76859. return DistanceJoint;
  76860. }(PhysicsJoint));
  76861. BABYLON.DistanceJoint = DistanceJoint;
  76862. var MotorEnabledJoint = /** @class */ (function (_super) {
  76863. __extends(MotorEnabledJoint, _super);
  76864. function MotorEnabledJoint(type, jointData) {
  76865. return _super.call(this, type, jointData) || this;
  76866. }
  76867. /**
  76868. * Set the motor values.
  76869. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76870. * @param {number} force the force to apply
  76871. * @param {number} maxForce max force for this motor.
  76872. */
  76873. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  76874. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  76875. };
  76876. /**
  76877. * Set the motor's limits.
  76878. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76879. */
  76880. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  76881. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  76882. };
  76883. return MotorEnabledJoint;
  76884. }(PhysicsJoint));
  76885. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  76886. /**
  76887. * This class represents a single hinge physics joint
  76888. */
  76889. var HingeJoint = /** @class */ (function (_super) {
  76890. __extends(HingeJoint, _super);
  76891. function HingeJoint(jointData) {
  76892. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  76893. }
  76894. /**
  76895. * Set the motor values.
  76896. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76897. * @param {number} force the force to apply
  76898. * @param {number} maxForce max force for this motor.
  76899. */
  76900. HingeJoint.prototype.setMotor = function (force, maxForce) {
  76901. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  76902. };
  76903. /**
  76904. * Set the motor's limits.
  76905. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76906. */
  76907. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  76908. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  76909. };
  76910. return HingeJoint;
  76911. }(MotorEnabledJoint));
  76912. BABYLON.HingeJoint = HingeJoint;
  76913. /**
  76914. * This class represents a dual hinge physics joint (same as wheel joint)
  76915. */
  76916. var Hinge2Joint = /** @class */ (function (_super) {
  76917. __extends(Hinge2Joint, _super);
  76918. function Hinge2Joint(jointData) {
  76919. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  76920. }
  76921. /**
  76922. * Set the motor values.
  76923. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76924. * @param {number} force the force to apply
  76925. * @param {number} maxForce max force for this motor.
  76926. * @param {motorIndex} the motor's index, 0 or 1.
  76927. */
  76928. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  76929. if (motorIndex === void 0) { motorIndex = 0; }
  76930. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  76931. };
  76932. /**
  76933. * Set the motor limits.
  76934. * Attention, this function is plugin specific. Engines won't react 100% the same.
  76935. * @param {number} upperLimit the upper limit
  76936. * @param {number} lowerLimit lower limit
  76937. * @param {motorIndex} the motor's index, 0 or 1.
  76938. */
  76939. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  76940. if (motorIndex === void 0) { motorIndex = 0; }
  76941. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  76942. };
  76943. return Hinge2Joint;
  76944. }(MotorEnabledJoint));
  76945. BABYLON.Hinge2Joint = Hinge2Joint;
  76946. })(BABYLON || (BABYLON = {}));
  76947. //# sourceMappingURL=babylon.physicsJoint.js.map
  76948. "use strict";
  76949. var BABYLON;
  76950. (function (BABYLON) {
  76951. var PhysicsImpostor = /** @class */ (function () {
  76952. function PhysicsImpostor(object, type, _options, _scene) {
  76953. if (_options === void 0) { _options = { mass: 0 }; }
  76954. var _this = this;
  76955. this.object = object;
  76956. this.type = type;
  76957. this._options = _options;
  76958. this._scene = _scene;
  76959. this._bodyUpdateRequired = false;
  76960. this._onBeforePhysicsStepCallbacks = new Array();
  76961. this._onAfterPhysicsStepCallbacks = new Array();
  76962. this._onPhysicsCollideCallbacks = [];
  76963. this._deltaPosition = BABYLON.Vector3.Zero();
  76964. this._isDisposed = false;
  76965. //temp variables for parent rotation calculations
  76966. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  76967. this._tmpQuat = new BABYLON.Quaternion();
  76968. this._tmpQuat2 = new BABYLON.Quaternion();
  76969. /**
  76970. * this function is executed by the physics engine.
  76971. */
  76972. this.beforeStep = function () {
  76973. if (!_this._physicsEngine) {
  76974. return;
  76975. }
  76976. _this.object.translate(_this._deltaPosition, -1);
  76977. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  76978. _this.object.computeWorldMatrix(false);
  76979. if (_this.object.parent && _this.object.rotationQuaternion) {
  76980. _this.getParentsRotation();
  76981. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  76982. }
  76983. else {
  76984. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  76985. }
  76986. if (!_this._options.disableBidirectionalTransformation) {
  76987. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  76988. }
  76989. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  76990. func(_this);
  76991. });
  76992. };
  76993. /**
  76994. * this function is executed by the physics engine.
  76995. */
  76996. this.afterStep = function () {
  76997. if (!_this._physicsEngine) {
  76998. return;
  76999. }
  77000. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  77001. func(_this);
  77002. });
  77003. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  77004. // object has now its world rotation. needs to be converted to local.
  77005. if (_this.object.parent && _this.object.rotationQuaternion) {
  77006. _this.getParentsRotation();
  77007. _this._tmpQuat.conjugateInPlace();
  77008. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  77009. }
  77010. // take the position set and make it the absolute position of this object.
  77011. _this.object.setAbsolutePosition(_this.object.position);
  77012. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  77013. _this.object.translate(_this._deltaPosition, 1);
  77014. };
  77015. /**
  77016. * Legacy collision detection event support
  77017. */
  77018. this.onCollideEvent = null;
  77019. //event and body object due to cannon's event-based architecture.
  77020. this.onCollide = function (e) {
  77021. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  77022. return;
  77023. }
  77024. if (!_this._physicsEngine) {
  77025. return;
  77026. }
  77027. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  77028. if (otherImpostor) {
  77029. // Legacy collision detection event support
  77030. if (_this.onCollideEvent) {
  77031. _this.onCollideEvent(_this, otherImpostor);
  77032. }
  77033. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  77034. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  77035. }).forEach(function (obj) {
  77036. obj.callback(_this, otherImpostor);
  77037. });
  77038. }
  77039. };
  77040. //sanity check!
  77041. if (!this.object) {
  77042. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  77043. return;
  77044. }
  77045. //legacy support for old syntax.
  77046. if (!this._scene && object.getScene) {
  77047. this._scene = object.getScene();
  77048. }
  77049. if (!this._scene) {
  77050. return;
  77051. }
  77052. this._physicsEngine = this._scene.getPhysicsEngine();
  77053. if (!this._physicsEngine) {
  77054. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  77055. }
  77056. else {
  77057. //set the object's quaternion, if not set
  77058. if (!this.object.rotationQuaternion) {
  77059. if (this.object.rotation) {
  77060. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  77061. }
  77062. else {
  77063. this.object.rotationQuaternion = new BABYLON.Quaternion();
  77064. }
  77065. }
  77066. //default options params
  77067. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  77068. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  77069. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  77070. this._joints = [];
  77071. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  77072. if (!this.object.parent || this._options.ignoreParent) {
  77073. this._init();
  77074. }
  77075. else if (this.object.parent.physicsImpostor) {
  77076. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  77077. }
  77078. }
  77079. }
  77080. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  77081. get: function () {
  77082. return this._isDisposed;
  77083. },
  77084. enumerable: true,
  77085. configurable: true
  77086. });
  77087. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  77088. get: function () {
  77089. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  77090. },
  77091. set: function (value) {
  77092. this.setMass(value);
  77093. },
  77094. enumerable: true,
  77095. configurable: true
  77096. });
  77097. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  77098. get: function () {
  77099. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  77100. },
  77101. set: function (value) {
  77102. if (!this._physicsEngine) {
  77103. return;
  77104. }
  77105. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  77106. },
  77107. enumerable: true,
  77108. configurable: true
  77109. });
  77110. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  77111. get: function () {
  77112. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  77113. },
  77114. set: function (value) {
  77115. if (!this._physicsEngine) {
  77116. return;
  77117. }
  77118. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  77119. },
  77120. enumerable: true,
  77121. configurable: true
  77122. });
  77123. /**
  77124. * This function will completly initialize this impostor.
  77125. * It will create a new body - but only if this mesh has no parent.
  77126. * If it has, this impostor will not be used other than to define the impostor
  77127. * of the child mesh.
  77128. */
  77129. PhysicsImpostor.prototype._init = function () {
  77130. if (!this._physicsEngine) {
  77131. return;
  77132. }
  77133. this._physicsEngine.removeImpostor(this);
  77134. this.physicsBody = null;
  77135. this._parent = this._parent || this._getPhysicsParent();
  77136. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  77137. this._physicsEngine.addImpostor(this);
  77138. }
  77139. };
  77140. PhysicsImpostor.prototype._getPhysicsParent = function () {
  77141. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  77142. var parentMesh = this.object.parent;
  77143. return parentMesh.physicsImpostor;
  77144. }
  77145. return null;
  77146. };
  77147. /**
  77148. * Should a new body be generated.
  77149. */
  77150. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  77151. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  77152. };
  77153. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  77154. this.forceUpdate();
  77155. };
  77156. /**
  77157. * Force a regeneration of this or the parent's impostor's body.
  77158. * Use under cautious - This will remove all joints already implemented.
  77159. */
  77160. PhysicsImpostor.prototype.forceUpdate = function () {
  77161. this._init();
  77162. if (this.parent && !this._options.ignoreParent) {
  77163. this.parent.forceUpdate();
  77164. }
  77165. };
  77166. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  77167. /*public get mesh(): AbstractMesh {
  77168. return this._mesh;
  77169. }*/
  77170. /**
  77171. * Gets the body that holds this impostor. Either its own, or its parent.
  77172. */
  77173. get: function () {
  77174. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  77175. },
  77176. /**
  77177. * Set the physics body. Used mainly by the physics engine/plugin
  77178. */
  77179. set: function (physicsBody) {
  77180. if (this._physicsBody && this._physicsEngine) {
  77181. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  77182. }
  77183. this._physicsBody = physicsBody;
  77184. this.resetUpdateFlags();
  77185. },
  77186. enumerable: true,
  77187. configurable: true
  77188. });
  77189. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  77190. get: function () {
  77191. return !this._options.ignoreParent && this._parent ? this._parent : null;
  77192. },
  77193. set: function (value) {
  77194. this._parent = value;
  77195. },
  77196. enumerable: true,
  77197. configurable: true
  77198. });
  77199. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  77200. this._bodyUpdateRequired = false;
  77201. };
  77202. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  77203. if (this.object.getBoundingInfo) {
  77204. var q = this.object.rotationQuaternion;
  77205. //reset rotation
  77206. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  77207. //calculate the world matrix with no rotation
  77208. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  77209. var boundingInfo = this.object.getBoundingInfo();
  77210. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  77211. //bring back the rotation
  77212. this.object.rotationQuaternion = q;
  77213. //calculate the world matrix with the new rotation
  77214. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  77215. return size;
  77216. }
  77217. else {
  77218. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  77219. }
  77220. };
  77221. PhysicsImpostor.prototype.getObjectCenter = function () {
  77222. if (this.object.getBoundingInfo) {
  77223. var boundingInfo = this.object.getBoundingInfo();
  77224. return boundingInfo.boundingBox.centerWorld;
  77225. }
  77226. else {
  77227. return this.object.position;
  77228. }
  77229. };
  77230. /**
  77231. * Get a specific parametes from the options parameter.
  77232. */
  77233. PhysicsImpostor.prototype.getParam = function (paramName) {
  77234. return this._options[paramName];
  77235. };
  77236. /**
  77237. * Sets a specific parameter in the options given to the physics plugin
  77238. */
  77239. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  77240. this._options[paramName] = value;
  77241. this._bodyUpdateRequired = true;
  77242. };
  77243. /**
  77244. * Specifically change the body's mass option. Won't recreate the physics body object
  77245. */
  77246. PhysicsImpostor.prototype.setMass = function (mass) {
  77247. if (this.getParam("mass") !== mass) {
  77248. this.setParam("mass", mass);
  77249. }
  77250. if (this._physicsEngine) {
  77251. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  77252. }
  77253. };
  77254. PhysicsImpostor.prototype.getLinearVelocity = function () {
  77255. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  77256. };
  77257. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  77258. if (this._physicsEngine) {
  77259. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  77260. }
  77261. };
  77262. PhysicsImpostor.prototype.getAngularVelocity = function () {
  77263. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  77264. };
  77265. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  77266. if (this._physicsEngine) {
  77267. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  77268. }
  77269. };
  77270. /**
  77271. * Execute a function with the physics plugin native code.
  77272. * Provide a function the will have two variables - the world object and the physics body object.
  77273. */
  77274. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  77275. if (this._physicsEngine) {
  77276. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  77277. }
  77278. };
  77279. /**
  77280. * Register a function that will be executed before the physics world is stepping forward.
  77281. */
  77282. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  77283. this._onBeforePhysicsStepCallbacks.push(func);
  77284. };
  77285. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  77286. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  77287. if (index > -1) {
  77288. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  77289. }
  77290. else {
  77291. BABYLON.Tools.Warn("Function to remove was not found");
  77292. }
  77293. };
  77294. /**
  77295. * Register a function that will be executed after the physics step
  77296. */
  77297. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  77298. this._onAfterPhysicsStepCallbacks.push(func);
  77299. };
  77300. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  77301. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  77302. if (index > -1) {
  77303. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  77304. }
  77305. else {
  77306. BABYLON.Tools.Warn("Function to remove was not found");
  77307. }
  77308. };
  77309. /**
  77310. * register a function that will be executed when this impostor collides against a different body.
  77311. */
  77312. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  77313. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  77314. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  77315. };
  77316. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  77317. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  77318. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  77319. if (index > -1) {
  77320. this._onPhysicsCollideCallbacks.splice(index, 1);
  77321. }
  77322. else {
  77323. BABYLON.Tools.Warn("Function to remove was not found");
  77324. }
  77325. };
  77326. PhysicsImpostor.prototype.getParentsRotation = function () {
  77327. var parent = this.object.parent;
  77328. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  77329. while (parent) {
  77330. if (parent.rotationQuaternion) {
  77331. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  77332. }
  77333. else {
  77334. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  77335. }
  77336. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  77337. parent = parent.parent;
  77338. }
  77339. return this._tmpQuat;
  77340. };
  77341. /**
  77342. * Apply a force
  77343. */
  77344. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  77345. if (this._physicsEngine) {
  77346. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  77347. }
  77348. return this;
  77349. };
  77350. /**
  77351. * Apply an impulse
  77352. */
  77353. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  77354. if (this._physicsEngine) {
  77355. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  77356. }
  77357. return this;
  77358. };
  77359. /**
  77360. * A help function to create a joint.
  77361. */
  77362. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  77363. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  77364. this.addJoint(otherImpostor, joint);
  77365. return this;
  77366. };
  77367. /**
  77368. * Add a joint to this impostor with a different impostor.
  77369. */
  77370. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  77371. this._joints.push({
  77372. otherImpostor: otherImpostor,
  77373. joint: joint
  77374. });
  77375. if (this._physicsEngine) {
  77376. this._physicsEngine.addJoint(this, otherImpostor, joint);
  77377. }
  77378. return this;
  77379. };
  77380. /**
  77381. * Will keep this body still, in a sleep mode.
  77382. */
  77383. PhysicsImpostor.prototype.sleep = function () {
  77384. if (this._physicsEngine) {
  77385. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  77386. }
  77387. return this;
  77388. };
  77389. /**
  77390. * Wake the body up.
  77391. */
  77392. PhysicsImpostor.prototype.wakeUp = function () {
  77393. if (this._physicsEngine) {
  77394. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  77395. }
  77396. return this;
  77397. };
  77398. PhysicsImpostor.prototype.clone = function (newObject) {
  77399. if (!newObject)
  77400. return null;
  77401. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  77402. };
  77403. PhysicsImpostor.prototype.dispose = function () {
  77404. var _this = this;
  77405. //no dispose if no physics engine is available.
  77406. if (!this._physicsEngine) {
  77407. return;
  77408. }
  77409. this._joints.forEach(function (j) {
  77410. if (_this._physicsEngine) {
  77411. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  77412. }
  77413. });
  77414. //dispose the physics body
  77415. this._physicsEngine.removeImpostor(this);
  77416. if (this.parent) {
  77417. this.parent.forceUpdate();
  77418. }
  77419. else {
  77420. /*this._object.getChildMeshes().forEach(function(mesh) {
  77421. if (mesh.physicsImpostor) {
  77422. if (disposeChildren) {
  77423. mesh.physicsImpostor.dispose();
  77424. mesh.physicsImpostor = null;
  77425. }
  77426. }
  77427. })*/
  77428. }
  77429. this._isDisposed = true;
  77430. };
  77431. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  77432. this._deltaPosition.copyFrom(position);
  77433. };
  77434. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  77435. if (!this._deltaRotation) {
  77436. this._deltaRotation = new BABYLON.Quaternion();
  77437. }
  77438. this._deltaRotation.copyFrom(rotation);
  77439. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  77440. };
  77441. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  77442. if (this._physicsEngine) {
  77443. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  77444. }
  77445. return this;
  77446. };
  77447. PhysicsImpostor.prototype.getRadius = function () {
  77448. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  77449. };
  77450. /**
  77451. * Sync a bone with this impostor
  77452. * @param bone The bone to sync to the impostor.
  77453. * @param boneMesh The mesh that the bone is influencing.
  77454. * @param jointPivot The pivot of the joint / bone in local space.
  77455. * @param distToJoint Optional distance from the impostor to the joint.
  77456. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  77457. */
  77458. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  77459. var tempVec = PhysicsImpostor._tmpVecs[0];
  77460. var mesh = this.object;
  77461. if (mesh.rotationQuaternion) {
  77462. if (adjustRotation) {
  77463. var tempQuat = PhysicsImpostor._tmpQuat;
  77464. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  77465. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  77466. }
  77467. else {
  77468. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  77469. }
  77470. }
  77471. tempVec.x = 0;
  77472. tempVec.y = 0;
  77473. tempVec.z = 0;
  77474. if (jointPivot) {
  77475. tempVec.x = jointPivot.x;
  77476. tempVec.y = jointPivot.y;
  77477. tempVec.z = jointPivot.z;
  77478. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  77479. if (distToJoint === undefined || distToJoint === null) {
  77480. distToJoint = jointPivot.length();
  77481. }
  77482. tempVec.x *= distToJoint;
  77483. tempVec.y *= distToJoint;
  77484. tempVec.z *= distToJoint;
  77485. }
  77486. if (bone.getParent()) {
  77487. tempVec.addInPlace(mesh.getAbsolutePosition());
  77488. bone.setAbsolutePosition(tempVec, boneMesh);
  77489. }
  77490. else {
  77491. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  77492. boneMesh.position.x -= tempVec.x;
  77493. boneMesh.position.y -= tempVec.y;
  77494. boneMesh.position.z -= tempVec.z;
  77495. }
  77496. };
  77497. /**
  77498. * Sync impostor to a bone
  77499. * @param bone The bone that the impostor will be synced to.
  77500. * @param boneMesh The mesh that the bone is influencing.
  77501. * @param jointPivot The pivot of the joint / bone in local space.
  77502. * @param distToJoint Optional distance from the impostor to the joint.
  77503. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  77504. * @param boneAxis Optional vector3 axis the bone is aligned with
  77505. */
  77506. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  77507. var mesh = this.object;
  77508. if (mesh.rotationQuaternion) {
  77509. if (adjustRotation) {
  77510. var tempQuat = PhysicsImpostor._tmpQuat;
  77511. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  77512. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  77513. }
  77514. else {
  77515. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  77516. }
  77517. }
  77518. var pos = PhysicsImpostor._tmpVecs[0];
  77519. var boneDir = PhysicsImpostor._tmpVecs[1];
  77520. if (!boneAxis) {
  77521. boneAxis = PhysicsImpostor._tmpVecs[2];
  77522. boneAxis.x = 0;
  77523. boneAxis.y = 1;
  77524. boneAxis.z = 0;
  77525. }
  77526. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  77527. bone.getAbsolutePositionToRef(boneMesh, pos);
  77528. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  77529. distToJoint = jointPivot.length();
  77530. }
  77531. if (distToJoint !== undefined && distToJoint !== null) {
  77532. pos.x += boneDir.x * distToJoint;
  77533. pos.y += boneDir.y * distToJoint;
  77534. pos.z += boneDir.z * distToJoint;
  77535. }
  77536. mesh.setAbsolutePosition(pos);
  77537. };
  77538. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  77539. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  77540. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  77541. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  77542. //Impostor types
  77543. PhysicsImpostor.NoImpostor = 0;
  77544. PhysicsImpostor.SphereImpostor = 1;
  77545. PhysicsImpostor.BoxImpostor = 2;
  77546. PhysicsImpostor.PlaneImpostor = 3;
  77547. PhysicsImpostor.MeshImpostor = 4;
  77548. PhysicsImpostor.CylinderImpostor = 7;
  77549. PhysicsImpostor.ParticleImpostor = 8;
  77550. PhysicsImpostor.HeightmapImpostor = 9;
  77551. return PhysicsImpostor;
  77552. }());
  77553. BABYLON.PhysicsImpostor = PhysicsImpostor;
  77554. })(BABYLON || (BABYLON = {}));
  77555. //# sourceMappingURL=babylon.physicsImpostor.js.map
  77556. "use strict";
  77557. var BABYLON;
  77558. (function (BABYLON) {
  77559. var PhysicsEngine = /** @class */ (function () {
  77560. function PhysicsEngine(gravity, _physicsPlugin) {
  77561. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  77562. this._physicsPlugin = _physicsPlugin;
  77563. //new methods and parameters
  77564. this._impostors = [];
  77565. this._joints = [];
  77566. if (!this._physicsPlugin.isSupported()) {
  77567. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  77568. + "Please make sure it is included.");
  77569. }
  77570. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  77571. this.setGravity(gravity);
  77572. this.setTimeStep();
  77573. }
  77574. PhysicsEngine.prototype.setGravity = function (gravity) {
  77575. this.gravity = gravity;
  77576. this._physicsPlugin.setGravity(this.gravity);
  77577. };
  77578. /**
  77579. * Set the time step of the physics engine.
  77580. * default is 1/60.
  77581. * To slow it down, enter 1/600 for example.
  77582. * To speed it up, 1/30
  77583. * @param {number} newTimeStep the new timestep to apply to this world.
  77584. */
  77585. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  77586. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  77587. this._physicsPlugin.setTimeStep(newTimeStep);
  77588. };
  77589. /**
  77590. * Get the time step of the physics engine.
  77591. */
  77592. PhysicsEngine.prototype.getTimeStep = function () {
  77593. return this._physicsPlugin.getTimeStep();
  77594. };
  77595. PhysicsEngine.prototype.dispose = function () {
  77596. this._impostors.forEach(function (impostor) {
  77597. impostor.dispose();
  77598. });
  77599. this._physicsPlugin.dispose();
  77600. };
  77601. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  77602. return this._physicsPlugin.name;
  77603. };
  77604. /**
  77605. * Adding a new impostor for the impostor tracking.
  77606. * This will be done by the impostor itself.
  77607. * @param {PhysicsImpostor} impostor the impostor to add
  77608. */
  77609. PhysicsEngine.prototype.addImpostor = function (impostor) {
  77610. impostor.uniqueId = this._impostors.push(impostor);
  77611. //if no parent, generate the body
  77612. if (!impostor.parent) {
  77613. this._physicsPlugin.generatePhysicsBody(impostor);
  77614. }
  77615. };
  77616. /**
  77617. * Remove an impostor from the engine.
  77618. * This impostor and its mesh will not longer be updated by the physics engine.
  77619. * @param {PhysicsImpostor} impostor the impostor to remove
  77620. */
  77621. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  77622. var index = this._impostors.indexOf(impostor);
  77623. if (index > -1) {
  77624. var removed = this._impostors.splice(index, 1);
  77625. //Is it needed?
  77626. if (removed.length) {
  77627. //this will also remove it from the world.
  77628. removed[0].physicsBody = null;
  77629. }
  77630. }
  77631. };
  77632. /**
  77633. * Add a joint to the physics engine
  77634. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  77635. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  77636. * @param {PhysicsJoint} the joint that will connect both impostors.
  77637. */
  77638. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  77639. var impostorJoint = {
  77640. mainImpostor: mainImpostor,
  77641. connectedImpostor: connectedImpostor,
  77642. joint: joint
  77643. };
  77644. joint.physicsPlugin = this._physicsPlugin;
  77645. this._joints.push(impostorJoint);
  77646. this._physicsPlugin.generateJoint(impostorJoint);
  77647. };
  77648. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  77649. var matchingJoints = this._joints.filter(function (impostorJoint) {
  77650. return (impostorJoint.connectedImpostor === connectedImpostor
  77651. && impostorJoint.joint === joint
  77652. && impostorJoint.mainImpostor === mainImpostor);
  77653. });
  77654. if (matchingJoints.length) {
  77655. this._physicsPlugin.removeJoint(matchingJoints[0]);
  77656. //TODO remove it from the list as well
  77657. }
  77658. };
  77659. /**
  77660. * Called by the scene. no need to call it.
  77661. */
  77662. PhysicsEngine.prototype._step = function (delta) {
  77663. var _this = this;
  77664. //check if any mesh has no body / requires an update
  77665. this._impostors.forEach(function (impostor) {
  77666. if (impostor.isBodyInitRequired()) {
  77667. _this._physicsPlugin.generatePhysicsBody(impostor);
  77668. }
  77669. });
  77670. if (delta > 0.1) {
  77671. delta = 0.1;
  77672. }
  77673. else if (delta <= 0) {
  77674. delta = 1.0 / 60.0;
  77675. }
  77676. this._physicsPlugin.executeStep(delta, this._impostors);
  77677. };
  77678. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  77679. return this._physicsPlugin;
  77680. };
  77681. PhysicsEngine.prototype.getImpostors = function () {
  77682. return this._impostors;
  77683. };
  77684. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  77685. for (var i = 0; i < this._impostors.length; ++i) {
  77686. if (this._impostors[i].object === object) {
  77687. return this._impostors[i];
  77688. }
  77689. }
  77690. return null;
  77691. };
  77692. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  77693. for (var i = 0; i < this._impostors.length; ++i) {
  77694. if (this._impostors[i].physicsBody === body) {
  77695. return this._impostors[i];
  77696. }
  77697. }
  77698. return null;
  77699. };
  77700. // Statics
  77701. PhysicsEngine.Epsilon = 0.001;
  77702. return PhysicsEngine;
  77703. }());
  77704. BABYLON.PhysicsEngine = PhysicsEngine;
  77705. })(BABYLON || (BABYLON = {}));
  77706. //# sourceMappingURL=babylon.physicsEngine.js.map
  77707. "use strict";
  77708. var BABYLON;
  77709. (function (BABYLON) {
  77710. var PhysicsHelper = /** @class */ (function () {
  77711. function PhysicsHelper(scene) {
  77712. this._scene = scene;
  77713. this._physicsEngine = this._scene.getPhysicsEngine();
  77714. if (!this._physicsEngine) {
  77715. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  77716. }
  77717. }
  77718. /**
  77719. * @param {Vector3} origin the origin of the explosion
  77720. * @param {number} radius the explosion radius
  77721. * @param {number} strength the explosion strength
  77722. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  77723. */
  77724. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  77725. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  77726. if (!this._physicsEngine) {
  77727. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  77728. return null;
  77729. }
  77730. var impostors = this._physicsEngine.getImpostors();
  77731. if (impostors.length === 0) {
  77732. return null;
  77733. }
  77734. var event = new PhysicsRadialExplosionEvent(this._scene);
  77735. impostors.forEach(function (impostor) {
  77736. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  77737. if (!impostorForceAndContactPoint) {
  77738. return;
  77739. }
  77740. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  77741. });
  77742. event.dispose(false);
  77743. return event;
  77744. };
  77745. /**
  77746. * @param {Vector3} origin the origin of the explosion
  77747. * @param {number} radius the explosion radius
  77748. * @param {number} strength the explosion strength
  77749. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  77750. */
  77751. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  77752. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  77753. if (!this._physicsEngine) {
  77754. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  77755. return null;
  77756. }
  77757. var impostors = this._physicsEngine.getImpostors();
  77758. if (impostors.length === 0) {
  77759. return null;
  77760. }
  77761. var event = new PhysicsRadialExplosionEvent(this._scene);
  77762. impostors.forEach(function (impostor) {
  77763. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  77764. if (!impostorForceAndContactPoint) {
  77765. return;
  77766. }
  77767. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  77768. });
  77769. event.dispose(false);
  77770. return event;
  77771. };
  77772. /**
  77773. * @param {Vector3} origin the origin of the explosion
  77774. * @param {number} radius the explosion radius
  77775. * @param {number} strength the explosion strength
  77776. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  77777. */
  77778. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  77779. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  77780. if (!this._physicsEngine) {
  77781. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  77782. return null;
  77783. }
  77784. var impostors = this._physicsEngine.getImpostors();
  77785. if (impostors.length === 0) {
  77786. return null;
  77787. }
  77788. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  77789. event.dispose(false);
  77790. return event;
  77791. };
  77792. /**
  77793. * @param {Vector3} origin the origin of the updraft
  77794. * @param {number} radius the radius of the updraft
  77795. * @param {number} strength the strength of the updraft
  77796. * @param {number} height the height of the updraft
  77797. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  77798. */
  77799. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  77800. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  77801. if (!this._physicsEngine) {
  77802. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  77803. return null;
  77804. }
  77805. if (this._physicsEngine.getImpostors().length === 0) {
  77806. return null;
  77807. }
  77808. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  77809. event.dispose(false);
  77810. return event;
  77811. };
  77812. /**
  77813. * @param {Vector3} origin the of the vortex
  77814. * @param {number} radius the radius of the vortex
  77815. * @param {number} strength the strength of the vortex
  77816. * @param {number} height the height of the vortex
  77817. */
  77818. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  77819. if (!this._physicsEngine) {
  77820. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  77821. return null;
  77822. }
  77823. if (this._physicsEngine.getImpostors().length === 0) {
  77824. return null;
  77825. }
  77826. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  77827. event.dispose(false);
  77828. return event;
  77829. };
  77830. return PhysicsHelper;
  77831. }());
  77832. BABYLON.PhysicsHelper = PhysicsHelper;
  77833. /***** Radial explosion *****/
  77834. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  77835. function PhysicsRadialExplosionEvent(scene) {
  77836. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  77837. this._rays = [];
  77838. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  77839. this._scene = scene;
  77840. }
  77841. /**
  77842. * Returns the data related to the radial explosion event (sphere & rays).
  77843. * @returns {PhysicsRadialExplosionEventData}
  77844. */
  77845. PhysicsRadialExplosionEvent.prototype.getData = function () {
  77846. this._dataFetched = true;
  77847. return {
  77848. sphere: this._sphere,
  77849. rays: this._rays,
  77850. };
  77851. };
  77852. /**
  77853. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  77854. * @param impostor
  77855. * @param {Vector3} origin the origin of the explosion
  77856. * @param {number} radius the explosion radius
  77857. * @param {number} strength the explosion strength
  77858. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  77859. * @returns {Nullable<PhysicsForceAndContactPoint>}
  77860. */
  77861. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  77862. if (impostor.mass === 0) {
  77863. return null;
  77864. }
  77865. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  77866. return null;
  77867. }
  77868. if (impostor.object.getClassName() !== 'Mesh') {
  77869. return null;
  77870. }
  77871. var impostorObject = impostor.object;
  77872. var impostorObjectCenter = impostor.getObjectCenter();
  77873. var direction = impostorObjectCenter.subtract(origin);
  77874. var ray = new BABYLON.Ray(origin, direction, radius);
  77875. this._rays.push(ray);
  77876. var hit = ray.intersectsMesh(impostorObject);
  77877. var contactPoint = hit.pickedPoint;
  77878. if (!contactPoint) {
  77879. return null;
  77880. }
  77881. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  77882. if (distanceFromOrigin > radius) {
  77883. return null;
  77884. }
  77885. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  77886. ? strength
  77887. : strength * (1 - (distanceFromOrigin / radius));
  77888. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  77889. return { force: force, contactPoint: contactPoint };
  77890. };
  77891. /**
  77892. * Disposes the sphere.
  77893. * @param {bolean} force
  77894. */
  77895. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  77896. var _this = this;
  77897. if (force === void 0) { force = true; }
  77898. if (force) {
  77899. this._sphere.dispose();
  77900. }
  77901. else {
  77902. setTimeout(function () {
  77903. if (!_this._dataFetched) {
  77904. _this._sphere.dispose();
  77905. }
  77906. }, 0);
  77907. }
  77908. };
  77909. /*** Helpers ***/
  77910. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  77911. if (!this._sphere) {
  77912. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  77913. this._sphere.isVisible = false;
  77914. }
  77915. };
  77916. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  77917. var impostorObject = impostor.object;
  77918. this._prepareSphere();
  77919. this._sphere.position = origin;
  77920. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  77921. this._sphere._updateBoundingInfo();
  77922. this._sphere.computeWorldMatrix(true);
  77923. return this._sphere.intersectsMesh(impostorObject, true);
  77924. };
  77925. return PhysicsRadialExplosionEvent;
  77926. }());
  77927. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  77928. /***** Gravitational Field *****/
  77929. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  77930. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  77931. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  77932. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  77933. this._physicsHelper = physicsHelper;
  77934. this._scene = scene;
  77935. this._origin = origin;
  77936. this._radius = radius;
  77937. this._strength = strength;
  77938. this._falloff = falloff;
  77939. this._tickCallback = this._tick.bind(this);
  77940. }
  77941. /**
  77942. * Returns the data related to the gravitational field event (sphere).
  77943. * @returns {PhysicsGravitationalFieldEventData}
  77944. */
  77945. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  77946. this._dataFetched = true;
  77947. return {
  77948. sphere: this._sphere,
  77949. };
  77950. };
  77951. /**
  77952. * Enables the gravitational field.
  77953. */
  77954. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  77955. this._tickCallback.call(this);
  77956. this._scene.registerBeforeRender(this._tickCallback);
  77957. };
  77958. /**
  77959. * Disables the gravitational field.
  77960. */
  77961. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  77962. this._scene.unregisterBeforeRender(this._tickCallback);
  77963. };
  77964. /**
  77965. * Disposes the sphere.
  77966. * @param {bolean} force
  77967. */
  77968. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  77969. var _this = this;
  77970. if (force === void 0) { force = true; }
  77971. if (force) {
  77972. this._sphere.dispose();
  77973. }
  77974. else {
  77975. setTimeout(function () {
  77976. if (!_this._dataFetched) {
  77977. _this._sphere.dispose();
  77978. }
  77979. }, 0);
  77980. }
  77981. };
  77982. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  77983. // Since the params won't change, we fetch the event only once
  77984. if (this._sphere) {
  77985. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  77986. }
  77987. else {
  77988. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  77989. if (radialExplosionEvent) {
  77990. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  77991. }
  77992. }
  77993. };
  77994. return PhysicsGravitationalFieldEvent;
  77995. }());
  77996. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  77997. /***** Updraft *****/
  77998. var PhysicsUpdraftEvent = /** @class */ (function () {
  77999. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  78000. this._scene = _scene;
  78001. this._origin = _origin;
  78002. this._radius = _radius;
  78003. this._strength = _strength;
  78004. this._height = _height;
  78005. this._updraftMode = _updraftMode;
  78006. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  78007. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  78008. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  78009. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  78010. this._physicsEngine = this._scene.getPhysicsEngine();
  78011. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  78012. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  78013. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  78014. this._originDirection = this._origin.subtract(this._originTop).normalize();
  78015. }
  78016. this._tickCallback = this._tick.bind(this);
  78017. }
  78018. /**
  78019. * Returns the data related to the updraft event (cylinder).
  78020. * @returns {PhysicsUpdraftEventData}
  78021. */
  78022. PhysicsUpdraftEvent.prototype.getData = function () {
  78023. this._dataFetched = true;
  78024. return {
  78025. cylinder: this._cylinder,
  78026. };
  78027. };
  78028. /**
  78029. * Enables the updraft.
  78030. */
  78031. PhysicsUpdraftEvent.prototype.enable = function () {
  78032. this._tickCallback.call(this);
  78033. this._scene.registerBeforeRender(this._tickCallback);
  78034. };
  78035. /**
  78036. * Disables the cortex.
  78037. */
  78038. PhysicsUpdraftEvent.prototype.disable = function () {
  78039. this._scene.unregisterBeforeRender(this._tickCallback);
  78040. };
  78041. /**
  78042. * Disposes the sphere.
  78043. * @param {bolean} force
  78044. */
  78045. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  78046. var _this = this;
  78047. if (force === void 0) { force = true; }
  78048. if (force) {
  78049. this._cylinder.dispose();
  78050. }
  78051. else {
  78052. setTimeout(function () {
  78053. if (!_this._dataFetched) {
  78054. _this._cylinder.dispose();
  78055. }
  78056. }, 0);
  78057. }
  78058. };
  78059. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  78060. if (impostor.mass === 0) {
  78061. return null;
  78062. }
  78063. if (!this._intersectsWithCylinder(impostor)) {
  78064. return null;
  78065. }
  78066. var impostorObjectCenter = impostor.getObjectCenter();
  78067. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  78068. var direction = this._originDirection;
  78069. }
  78070. else {
  78071. var direction = impostorObjectCenter.subtract(this._originTop);
  78072. }
  78073. var multiplier = this._strength * -1;
  78074. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  78075. return { force: force, contactPoint: impostorObjectCenter };
  78076. };
  78077. PhysicsUpdraftEvent.prototype._tick = function () {
  78078. var _this = this;
  78079. this._physicsEngine.getImpostors().forEach(function (impostor) {
  78080. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  78081. if (!impostorForceAndContactPoint) {
  78082. return;
  78083. }
  78084. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  78085. });
  78086. };
  78087. /*** Helpers ***/
  78088. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  78089. if (!this._cylinder) {
  78090. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  78091. height: this._height,
  78092. diameter: this._radius * 2,
  78093. }, this._scene);
  78094. this._cylinder.isVisible = false;
  78095. }
  78096. };
  78097. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  78098. var impostorObject = impostor.object;
  78099. this._prepareCylinder();
  78100. this._cylinder.position = this._cylinderPosition;
  78101. return this._cylinder.intersectsMesh(impostorObject, true);
  78102. };
  78103. return PhysicsUpdraftEvent;
  78104. }());
  78105. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  78106. /***** Vortex *****/
  78107. var PhysicsVortexEvent = /** @class */ (function () {
  78108. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  78109. this._scene = _scene;
  78110. this._origin = _origin;
  78111. this._radius = _radius;
  78112. this._strength = _strength;
  78113. this._height = _height;
  78114. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  78115. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  78116. this._updraftMultiplier = 0.02;
  78117. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  78118. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  78119. this._physicsEngine = this._scene.getPhysicsEngine();
  78120. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  78121. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  78122. this._tickCallback = this._tick.bind(this);
  78123. }
  78124. /**
  78125. * Returns the data related to the vortex event (cylinder).
  78126. * @returns {PhysicsVortexEventData}
  78127. */
  78128. PhysicsVortexEvent.prototype.getData = function () {
  78129. this._dataFetched = true;
  78130. return {
  78131. cylinder: this._cylinder,
  78132. };
  78133. };
  78134. /**
  78135. * Enables the vortex.
  78136. */
  78137. PhysicsVortexEvent.prototype.enable = function () {
  78138. this._tickCallback.call(this);
  78139. this._scene.registerBeforeRender(this._tickCallback);
  78140. };
  78141. /**
  78142. * Disables the cortex.
  78143. */
  78144. PhysicsVortexEvent.prototype.disable = function () {
  78145. this._scene.unregisterBeforeRender(this._tickCallback);
  78146. };
  78147. /**
  78148. * Disposes the sphere.
  78149. * @param {bolean} force
  78150. */
  78151. PhysicsVortexEvent.prototype.dispose = function (force) {
  78152. var _this = this;
  78153. if (force === void 0) { force = true; }
  78154. if (force) {
  78155. this._cylinder.dispose();
  78156. }
  78157. else {
  78158. setTimeout(function () {
  78159. if (!_this._dataFetched) {
  78160. _this._cylinder.dispose();
  78161. }
  78162. }, 0);
  78163. }
  78164. };
  78165. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  78166. if (impostor.mass === 0) {
  78167. return null;
  78168. }
  78169. if (!this._intersectsWithCylinder(impostor)) {
  78170. return null;
  78171. }
  78172. if (impostor.object.getClassName() !== 'Mesh') {
  78173. return null;
  78174. }
  78175. var impostorObject = impostor.object;
  78176. var impostorObjectCenter = impostor.getObjectCenter();
  78177. 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)
  78178. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  78179. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  78180. var hit = ray.intersectsMesh(impostorObject);
  78181. var contactPoint = hit.pickedPoint;
  78182. if (!contactPoint) {
  78183. return null;
  78184. }
  78185. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  78186. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  78187. var directionToOrigin = contactPoint.normalize();
  78188. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  78189. directionToOrigin = directionToOrigin.negate();
  78190. }
  78191. // TODO: find a more physically based solution
  78192. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  78193. var forceX = directionToOrigin.x * this._strength / 8;
  78194. var forceY = directionToOrigin.y * this._updraftMultiplier;
  78195. var forceZ = directionToOrigin.z * this._strength / 8;
  78196. }
  78197. else {
  78198. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  78199. var forceY = this._originTop.y * this._updraftMultiplier;
  78200. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  78201. }
  78202. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  78203. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  78204. return { force: force, contactPoint: impostorObjectCenter };
  78205. };
  78206. PhysicsVortexEvent.prototype._tick = function () {
  78207. var _this = this;
  78208. this._physicsEngine.getImpostors().forEach(function (impostor) {
  78209. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  78210. if (!impostorForceAndContactPoint) {
  78211. return;
  78212. }
  78213. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  78214. });
  78215. };
  78216. /*** Helpers ***/
  78217. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  78218. if (!this._cylinder) {
  78219. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  78220. height: this._height,
  78221. diameter: this._radius * 2,
  78222. }, this._scene);
  78223. this._cylinder.isVisible = false;
  78224. }
  78225. };
  78226. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  78227. var impostorObject = impostor.object;
  78228. this._prepareCylinder();
  78229. this._cylinder.position = this._cylinderPosition;
  78230. return this._cylinder.intersectsMesh(impostorObject, true);
  78231. };
  78232. return PhysicsVortexEvent;
  78233. }());
  78234. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  78235. /***** Enums *****/
  78236. /**
  78237. * The strenght of the force in correspondence to the distance of the affected object
  78238. */
  78239. var PhysicsRadialImpulseFalloff;
  78240. (function (PhysicsRadialImpulseFalloff) {
  78241. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  78242. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear"; // impulse gets weaker if it's further from the origin
  78243. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  78244. /**
  78245. * The strenght of the force in correspondence to the distance of the affected object
  78246. */
  78247. var PhysicsUpdraftMode;
  78248. (function (PhysicsUpdraftMode) {
  78249. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  78250. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular"; // once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder
  78251. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  78252. })(BABYLON || (BABYLON = {}));
  78253. //# sourceMappingURL=babylon.physicsHelper.js.map
  78254. "use strict";
  78255. var BABYLON;
  78256. (function (BABYLON) {
  78257. var CannonJSPlugin = /** @class */ (function () {
  78258. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  78259. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  78260. if (iterations === void 0) { iterations = 10; }
  78261. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  78262. this.name = "CannonJSPlugin";
  78263. this._physicsMaterials = new Array();
  78264. this._fixedTimeStep = 1 / 60;
  78265. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  78266. this.BJSCANNON = typeof CANNON !== 'undefined' ? CANNON : (typeof require !== 'undefined' ? require('cannon') : undefined);
  78267. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  78268. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  78269. this._tmpPosition = BABYLON.Vector3.Zero();
  78270. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  78271. this._tmpUnityRotation = new BABYLON.Quaternion();
  78272. if (!this.isSupported()) {
  78273. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  78274. return;
  78275. }
  78276. this._extendNamespace();
  78277. this.world = new this.BJSCANNON.World();
  78278. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  78279. this.world.solver.iterations = iterations;
  78280. }
  78281. CannonJSPlugin.prototype.setGravity = function (gravity) {
  78282. this.world.gravity.copy(gravity);
  78283. };
  78284. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  78285. this._fixedTimeStep = timeStep;
  78286. };
  78287. CannonJSPlugin.prototype.getTimeStep = function () {
  78288. return this._fixedTimeStep;
  78289. };
  78290. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  78291. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  78292. };
  78293. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  78294. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  78295. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  78296. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  78297. };
  78298. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  78299. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  78300. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  78301. impostor.physicsBody.applyForce(impulse, worldPoint);
  78302. };
  78303. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  78304. //parent-child relationship. Does this impostor has a parent impostor?
  78305. if (impostor.parent) {
  78306. if (impostor.physicsBody) {
  78307. this.removePhysicsBody(impostor);
  78308. //TODO is that needed?
  78309. impostor.forceUpdate();
  78310. }
  78311. return;
  78312. }
  78313. //should a new body be created for this impostor?
  78314. if (impostor.isBodyInitRequired()) {
  78315. var shape = this._createShape(impostor);
  78316. //unregister events, if body is being changed
  78317. var oldBody = impostor.physicsBody;
  78318. if (oldBody) {
  78319. this.removePhysicsBody(impostor);
  78320. }
  78321. //create the body and material
  78322. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  78323. var bodyCreationObject = {
  78324. mass: impostor.getParam("mass"),
  78325. material: material
  78326. };
  78327. // A simple extend, in case native options were used.
  78328. var nativeOptions = impostor.getParam("nativeOptions");
  78329. for (var key in nativeOptions) {
  78330. if (nativeOptions.hasOwnProperty(key)) {
  78331. bodyCreationObject[key] = nativeOptions[key];
  78332. }
  78333. }
  78334. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  78335. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  78336. this.world.addEventListener("preStep", impostor.beforeStep);
  78337. this.world.addEventListener("postStep", impostor.afterStep);
  78338. impostor.physicsBody.addShape(shape);
  78339. this.world.add(impostor.physicsBody);
  78340. //try to keep the body moving in the right direction by taking old properties.
  78341. //Should be tested!
  78342. if (oldBody) {
  78343. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  78344. impostor.physicsBody[param].copy(oldBody[param]);
  78345. });
  78346. }
  78347. this._processChildMeshes(impostor);
  78348. }
  78349. //now update the body's transformation
  78350. this._updatePhysicsBodyTransformation(impostor);
  78351. };
  78352. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  78353. var _this = this;
  78354. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  78355. var currentRotation = mainImpostor.object.rotationQuaternion;
  78356. if (meshChildren.length) {
  78357. var processMesh = function (localPosition, mesh) {
  78358. if (!currentRotation || !mesh.rotationQuaternion) {
  78359. return;
  78360. }
  78361. var childImpostor = mesh.getPhysicsImpostor();
  78362. if (childImpostor) {
  78363. var parent = childImpostor.parent;
  78364. if (parent !== mainImpostor) {
  78365. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  78366. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  78367. if (childImpostor.physicsBody) {
  78368. _this.removePhysicsBody(childImpostor);
  78369. childImpostor.physicsBody = null;
  78370. }
  78371. childImpostor.parent = mainImpostor;
  78372. childImpostor.resetUpdateFlags();
  78373. 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));
  78374. //Add the mass of the children.
  78375. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  78376. }
  78377. }
  78378. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  78379. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  78380. };
  78381. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  78382. }
  78383. };
  78384. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  78385. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  78386. this.world.removeEventListener("preStep", impostor.beforeStep);
  78387. this.world.removeEventListener("postStep", impostor.afterStep);
  78388. this.world.remove(impostor.physicsBody);
  78389. };
  78390. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  78391. var mainBody = impostorJoint.mainImpostor.physicsBody;
  78392. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  78393. if (!mainBody || !connectedBody) {
  78394. return;
  78395. }
  78396. var constraint;
  78397. var jointData = impostorJoint.joint.jointData;
  78398. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  78399. var constraintData = {
  78400. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  78401. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  78402. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  78403. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  78404. maxForce: jointData.nativeParams.maxForce,
  78405. collideConnected: !!jointData.collision
  78406. };
  78407. switch (impostorJoint.joint.type) {
  78408. case BABYLON.PhysicsJoint.HingeJoint:
  78409. case BABYLON.PhysicsJoint.Hinge2Joint:
  78410. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  78411. break;
  78412. case BABYLON.PhysicsJoint.DistanceJoint:
  78413. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  78414. break;
  78415. case BABYLON.PhysicsJoint.SpringJoint:
  78416. var springData = jointData;
  78417. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  78418. restLength: springData.length,
  78419. stiffness: springData.stiffness,
  78420. damping: springData.damping,
  78421. localAnchorA: constraintData.pivotA,
  78422. localAnchorB: constraintData.pivotB
  78423. });
  78424. break;
  78425. case BABYLON.PhysicsJoint.LockJoint:
  78426. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  78427. break;
  78428. case BABYLON.PhysicsJoint.PointToPointJoint:
  78429. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  78430. default:
  78431. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  78432. break;
  78433. }
  78434. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  78435. constraint.collideConnected = !!jointData.collision;
  78436. impostorJoint.joint.physicsJoint = constraint;
  78437. //don't add spring as constraint, as it is not one.
  78438. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  78439. this.world.addConstraint(constraint);
  78440. }
  78441. else {
  78442. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  78443. constraint.applyForce();
  78444. });
  78445. }
  78446. };
  78447. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  78448. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  78449. };
  78450. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  78451. var index;
  78452. var mat;
  78453. for (index = 0; index < this._physicsMaterials.length; index++) {
  78454. mat = this._physicsMaterials[index];
  78455. if (mat.friction === friction && mat.restitution === restitution) {
  78456. return mat;
  78457. }
  78458. }
  78459. var currentMat = new this.BJSCANNON.Material(name);
  78460. currentMat.friction = friction;
  78461. currentMat.restitution = restitution;
  78462. this._physicsMaterials.push(currentMat);
  78463. return currentMat;
  78464. };
  78465. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  78466. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  78467. };
  78468. CannonJSPlugin.prototype._createShape = function (impostor) {
  78469. var object = impostor.object;
  78470. var returnValue;
  78471. var extendSize = impostor.getObjectExtendSize();
  78472. switch (impostor.type) {
  78473. case BABYLON.PhysicsImpostor.SphereImpostor:
  78474. var radiusX = extendSize.x;
  78475. var radiusY = extendSize.y;
  78476. var radiusZ = extendSize.z;
  78477. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  78478. break;
  78479. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  78480. case BABYLON.PhysicsImpostor.CylinderImpostor:
  78481. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  78482. break;
  78483. case BABYLON.PhysicsImpostor.BoxImpostor:
  78484. var box = extendSize.scale(0.5);
  78485. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  78486. break;
  78487. case BABYLON.PhysicsImpostor.PlaneImpostor:
  78488. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  78489. returnValue = new this.BJSCANNON.Plane();
  78490. break;
  78491. case BABYLON.PhysicsImpostor.MeshImpostor:
  78492. // should transform the vertex data to world coordinates!!
  78493. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  78494. var rawFaces = object.getIndices ? object.getIndices() : [];
  78495. if (!rawVerts)
  78496. return;
  78497. // get only scale! so the object could transform correctly.
  78498. var oldPosition = object.position.clone();
  78499. var oldRotation = object.rotation && object.rotation.clone();
  78500. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  78501. object.position.copyFromFloats(0, 0, 0);
  78502. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  78503. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  78504. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  78505. var transform = object.computeWorldMatrix(true);
  78506. // convert rawVerts to object space
  78507. var temp = new Array();
  78508. var index;
  78509. for (index = 0; index < rawVerts.length; index += 3) {
  78510. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  78511. }
  78512. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  78513. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  78514. //now set back the transformation!
  78515. object.position.copyFrom(oldPosition);
  78516. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  78517. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  78518. break;
  78519. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  78520. var oldPosition2 = object.position.clone();
  78521. var oldRotation2 = object.rotation && object.rotation.clone();
  78522. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  78523. object.position.copyFromFloats(0, 0, 0);
  78524. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  78525. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  78526. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  78527. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  78528. returnValue = this._createHeightmap(object);
  78529. object.position.copyFrom(oldPosition2);
  78530. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  78531. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  78532. object.computeWorldMatrix(true);
  78533. break;
  78534. case BABYLON.PhysicsImpostor.ParticleImpostor:
  78535. returnValue = new this.BJSCANNON.Particle();
  78536. break;
  78537. }
  78538. return returnValue;
  78539. };
  78540. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  78541. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  78542. var transform = object.computeWorldMatrix(true);
  78543. // convert rawVerts to object space
  78544. var temp = new Array();
  78545. var index;
  78546. for (index = 0; index < pos.length; index += 3) {
  78547. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  78548. }
  78549. pos = temp;
  78550. var matrix = new Array();
  78551. //For now pointDepth will not be used and will be automatically calculated.
  78552. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  78553. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  78554. var boundingInfo = object.getBoundingInfo();
  78555. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  78556. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  78557. var elementSize = dim * 2 / arraySize;
  78558. for (var i = 0; i < pos.length; i = i + 3) {
  78559. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  78560. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  78561. var y = -pos[i + 2] + minY;
  78562. if (!matrix[x]) {
  78563. matrix[x] = [];
  78564. }
  78565. if (!matrix[x][z]) {
  78566. matrix[x][z] = y;
  78567. }
  78568. matrix[x][z] = Math.max(y, matrix[x][z]);
  78569. }
  78570. for (var x = 0; x <= arraySize; ++x) {
  78571. if (!matrix[x]) {
  78572. var loc = 1;
  78573. while (!matrix[(x + loc) % arraySize]) {
  78574. loc++;
  78575. }
  78576. matrix[x] = matrix[(x + loc) % arraySize].slice();
  78577. //console.log("missing x", x);
  78578. }
  78579. for (var z = 0; z <= arraySize; ++z) {
  78580. if (!matrix[x][z]) {
  78581. var loc = 1;
  78582. var newValue;
  78583. while (newValue === undefined) {
  78584. newValue = matrix[x][(z + loc++) % arraySize];
  78585. }
  78586. matrix[x][z] = newValue;
  78587. }
  78588. }
  78589. }
  78590. var shape = new this.BJSCANNON.Heightfield(matrix, {
  78591. elementSize: elementSize
  78592. });
  78593. //For future reference, needed for body transformation
  78594. shape.minY = minY;
  78595. return shape;
  78596. };
  78597. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  78598. var object = impostor.object;
  78599. //make sure it is updated...
  78600. object.computeWorldMatrix && object.computeWorldMatrix(true);
  78601. // The delta between the mesh position and the mesh bounding box center
  78602. var bInfo = object.getBoundingInfo();
  78603. if (!bInfo)
  78604. return;
  78605. var center = impostor.getObjectCenter();
  78606. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  78607. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  78608. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  78609. this._tmpPosition.copyFrom(center);
  78610. var quaternion = object.rotationQuaternion;
  78611. if (!quaternion) {
  78612. return;
  78613. }
  78614. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  78615. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  78616. //-90 DEG in X, precalculated
  78617. quaternion = quaternion.multiply(this._minus90X);
  78618. //Invert! (Precalculated, 90 deg in X)
  78619. //No need to clone. this will never change.
  78620. impostor.setDeltaRotation(this._plus90X);
  78621. }
  78622. //If it is a heightfield, if should be centered.
  78623. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  78624. var mesh = object;
  78625. var boundingInfo = mesh.getBoundingInfo();
  78626. //calculate the correct body position:
  78627. var rotationQuaternion = mesh.rotationQuaternion;
  78628. mesh.rotationQuaternion = this._tmpUnityRotation;
  78629. mesh.computeWorldMatrix(true);
  78630. //get original center with no rotation
  78631. var c = center.clone();
  78632. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  78633. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  78634. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  78635. mesh.setPreTransformMatrix(p);
  78636. mesh.computeWorldMatrix(true);
  78637. //calculate the translation
  78638. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  78639. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  78640. //add it inverted to the delta
  78641. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  78642. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  78643. //rotation is back
  78644. mesh.rotationQuaternion = rotationQuaternion;
  78645. mesh.setPreTransformMatrix(oldPivot);
  78646. mesh.computeWorldMatrix(true);
  78647. }
  78648. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  78649. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  78650. //this._tmpPosition.copyFrom(object.position);
  78651. }
  78652. impostor.setDeltaPosition(this._tmpDeltaPosition);
  78653. //Now update the impostor object
  78654. impostor.physicsBody.position.copy(this._tmpPosition);
  78655. impostor.physicsBody.quaternion.copy(quaternion);
  78656. };
  78657. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  78658. impostor.object.position.copyFrom(impostor.physicsBody.position);
  78659. if (impostor.object.rotationQuaternion) {
  78660. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  78661. }
  78662. };
  78663. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  78664. impostor.physicsBody.position.copy(newPosition);
  78665. impostor.physicsBody.quaternion.copy(newRotation);
  78666. };
  78667. CannonJSPlugin.prototype.isSupported = function () {
  78668. return this.BJSCANNON !== undefined;
  78669. };
  78670. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  78671. impostor.physicsBody.velocity.copy(velocity);
  78672. };
  78673. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  78674. impostor.physicsBody.angularVelocity.copy(velocity);
  78675. };
  78676. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  78677. var v = impostor.physicsBody.velocity;
  78678. if (!v) {
  78679. return null;
  78680. }
  78681. return new BABYLON.Vector3(v.x, v.y, v.z);
  78682. };
  78683. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  78684. var v = impostor.physicsBody.angularVelocity;
  78685. if (!v) {
  78686. return null;
  78687. }
  78688. return new BABYLON.Vector3(v.x, v.y, v.z);
  78689. };
  78690. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  78691. impostor.physicsBody.mass = mass;
  78692. impostor.physicsBody.updateMassProperties();
  78693. };
  78694. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  78695. return impostor.physicsBody.mass;
  78696. };
  78697. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  78698. return impostor.physicsBody.material.friction;
  78699. };
  78700. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  78701. impostor.physicsBody.material.friction = friction;
  78702. };
  78703. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  78704. return impostor.physicsBody.material.restitution;
  78705. };
  78706. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  78707. impostor.physicsBody.material.restitution = restitution;
  78708. };
  78709. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  78710. impostor.physicsBody.sleep();
  78711. };
  78712. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  78713. impostor.physicsBody.wakeUp();
  78714. };
  78715. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  78716. joint.physicsJoint.distance = maxDistance;
  78717. };
  78718. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  78719. // if (!motorIndex) {
  78720. // joint.physicsJoint.enableMotor();
  78721. // }
  78722. // }
  78723. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  78724. // if (!motorIndex) {
  78725. // joint.physicsJoint.disableMotor();
  78726. // }
  78727. // }
  78728. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  78729. if (!motorIndex) {
  78730. joint.physicsJoint.enableMotor();
  78731. joint.physicsJoint.setMotorSpeed(speed);
  78732. if (maxForce) {
  78733. this.setLimit(joint, maxForce);
  78734. }
  78735. }
  78736. };
  78737. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  78738. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  78739. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  78740. };
  78741. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  78742. var body = impostor.physicsBody;
  78743. mesh.position.x = body.position.x;
  78744. mesh.position.y = body.position.y;
  78745. mesh.position.z = body.position.z;
  78746. if (mesh.rotationQuaternion) {
  78747. mesh.rotationQuaternion.x = body.quaternion.x;
  78748. mesh.rotationQuaternion.y = body.quaternion.y;
  78749. mesh.rotationQuaternion.z = body.quaternion.z;
  78750. mesh.rotationQuaternion.w = body.quaternion.w;
  78751. }
  78752. };
  78753. CannonJSPlugin.prototype.getRadius = function (impostor) {
  78754. var shape = impostor.physicsBody.shapes[0];
  78755. return shape.boundingSphereRadius;
  78756. };
  78757. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  78758. var shape = impostor.physicsBody.shapes[0];
  78759. result.x = shape.halfExtents.x * 2;
  78760. result.y = shape.halfExtents.y * 2;
  78761. result.z = shape.halfExtents.z * 2;
  78762. };
  78763. CannonJSPlugin.prototype.dispose = function () {
  78764. };
  78765. CannonJSPlugin.prototype._extendNamespace = function () {
  78766. //this will force cannon to execute at least one step when using interpolation
  78767. var step_tmp1 = new this.BJSCANNON.Vec3();
  78768. var Engine = this.BJSCANNON;
  78769. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  78770. maxSubSteps = maxSubSteps || 10;
  78771. timeSinceLastCalled = timeSinceLastCalled || 0;
  78772. if (timeSinceLastCalled === 0) {
  78773. this.internalStep(dt);
  78774. this.time += dt;
  78775. }
  78776. else {
  78777. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  78778. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  78779. var t0 = performance.now();
  78780. for (var i = 0; i !== internalSteps; i++) {
  78781. this.internalStep(dt);
  78782. if (performance.now() - t0 > dt * 1000) {
  78783. break;
  78784. }
  78785. }
  78786. this.time += timeSinceLastCalled;
  78787. var h = this.time % dt;
  78788. var h_div_dt = h / dt;
  78789. var interpvelo = step_tmp1;
  78790. var bodies = this.bodies;
  78791. for (var j = 0; j !== bodies.length; j++) {
  78792. var b = bodies[j];
  78793. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  78794. b.position.vsub(b.previousPosition, interpvelo);
  78795. interpvelo.scale(h_div_dt, interpvelo);
  78796. b.position.vadd(interpvelo, b.interpolatedPosition);
  78797. }
  78798. else {
  78799. b.interpolatedPosition.copy(b.position);
  78800. b.interpolatedQuaternion.copy(b.quaternion);
  78801. }
  78802. }
  78803. }
  78804. };
  78805. };
  78806. return CannonJSPlugin;
  78807. }());
  78808. BABYLON.CannonJSPlugin = CannonJSPlugin;
  78809. })(BABYLON || (BABYLON = {}));
  78810. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  78811. "use strict";
  78812. var BABYLON;
  78813. (function (BABYLON) {
  78814. var OimoJSPlugin = /** @class */ (function () {
  78815. function OimoJSPlugin(iterations) {
  78816. this.name = "OimoJSPlugin";
  78817. this._tmpImpostorsArray = [];
  78818. this._tmpPositionVector = BABYLON.Vector3.Zero();
  78819. this.BJSOIMO = typeof OIMO !== 'undefined' ? OIMO : (typeof require !== 'undefined' ? require('./Oimo') : undefined);
  78820. this.world = new this.BJSOIMO.World(1 / 60, 2, iterations, true);
  78821. this.world.worldscale(1);
  78822. this.world.clear();
  78823. //making sure no stats are calculated
  78824. this.world.isNoStat = true;
  78825. }
  78826. OimoJSPlugin.prototype.setGravity = function (gravity) {
  78827. this.world.gravity.copy(gravity);
  78828. };
  78829. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  78830. this.world.timeStep = timeStep;
  78831. };
  78832. OimoJSPlugin.prototype.getTimeStep = function () {
  78833. return this.world.timeStep;
  78834. };
  78835. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  78836. var _this = this;
  78837. impostors.forEach(function (impostor) {
  78838. impostor.beforeStep();
  78839. });
  78840. this.world.step();
  78841. impostors.forEach(function (impostor) {
  78842. impostor.afterStep();
  78843. //update the ordered impostors array
  78844. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  78845. });
  78846. //check for collisions
  78847. var contact = this.world.contacts;
  78848. while (contact !== null) {
  78849. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  78850. contact = contact.next;
  78851. continue;
  78852. }
  78853. //is this body colliding with any other? get the impostor
  78854. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  78855. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  78856. if (!mainImpostor || !collidingImpostor) {
  78857. contact = contact.next;
  78858. continue;
  78859. }
  78860. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  78861. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  78862. contact = contact.next;
  78863. }
  78864. };
  78865. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  78866. var mass = impostor.physicsBody.massInfo.mass;
  78867. impostor.physicsBody.applyImpulse(contactPoint.scale(this.BJSOIMO.INV_SCALE), force.scale(this.BJSOIMO.INV_SCALE * mass));
  78868. };
  78869. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  78870. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  78871. this.applyImpulse(impostor, force, contactPoint);
  78872. };
  78873. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  78874. var _this = this;
  78875. //parent-child relationship. Does this impostor has a parent impostor?
  78876. if (impostor.parent) {
  78877. if (impostor.physicsBody) {
  78878. this.removePhysicsBody(impostor);
  78879. //TODO is that needed?
  78880. impostor.forceUpdate();
  78881. }
  78882. return;
  78883. }
  78884. if (impostor.isBodyInitRequired()) {
  78885. var bodyConfig = {
  78886. name: impostor.uniqueId,
  78887. //Oimo must have mass, also for static objects.
  78888. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  78889. size: [],
  78890. type: [],
  78891. pos: [],
  78892. rot: [],
  78893. move: impostor.getParam("mass") !== 0,
  78894. //Supporting older versions of Oimo
  78895. world: this.world
  78896. };
  78897. var impostors = [impostor];
  78898. var addToArray = function (parent) {
  78899. if (!parent.getChildMeshes)
  78900. return;
  78901. parent.getChildMeshes().forEach(function (m) {
  78902. if (m.physicsImpostor) {
  78903. impostors.push(m.physicsImpostor);
  78904. //m.physicsImpostor._init();
  78905. }
  78906. });
  78907. };
  78908. addToArray(impostor.object);
  78909. var checkWithEpsilon_1 = function (value) {
  78910. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  78911. };
  78912. impostors.forEach(function (i) {
  78913. if (!impostor.object.rotationQuaternion) {
  78914. return;
  78915. }
  78916. //get the correct bounding box
  78917. var oldQuaternion = i.object.rotationQuaternion;
  78918. var rot = new _this.BJSOIMO.Euler().setFromQuaternion({
  78919. x: impostor.object.rotationQuaternion.x,
  78920. y: impostor.object.rotationQuaternion.y,
  78921. z: impostor.object.rotationQuaternion.z,
  78922. s: impostor.object.rotationQuaternion.w
  78923. });
  78924. var extendSize = i.getObjectExtendSize();
  78925. if (i === impostor) {
  78926. var center = impostor.getObjectCenter();
  78927. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  78928. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  78929. //Can also use Array.prototype.push.apply
  78930. bodyConfig.pos.push(center.x);
  78931. bodyConfig.pos.push(center.y);
  78932. bodyConfig.pos.push(center.z);
  78933. //tmp solution
  78934. bodyConfig.rot.push(rot.x / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  78935. bodyConfig.rot.push(rot.y / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  78936. bodyConfig.rot.push(rot.z / (_this.BJSOIMO.degtorad || _this.BJSOIMO.TO_RAD));
  78937. }
  78938. else {
  78939. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  78940. bodyConfig.pos.push(localPosition.x);
  78941. bodyConfig.pos.push(localPosition.y);
  78942. bodyConfig.pos.push(localPosition.z);
  78943. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  78944. bodyConfig.rot.push(0);
  78945. bodyConfig.rot.push(0);
  78946. bodyConfig.rot.push(0);
  78947. }
  78948. // register mesh
  78949. switch (i.type) {
  78950. case BABYLON.PhysicsImpostor.ParticleImpostor:
  78951. BABYLON.Tools.Warn("No Particle support in this.BJSOIMO.js. using SphereImpostor instead");
  78952. case BABYLON.PhysicsImpostor.SphereImpostor:
  78953. var radiusX = extendSize.x;
  78954. var radiusY = extendSize.y;
  78955. var radiusZ = extendSize.z;
  78956. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  78957. bodyConfig.type.push('sphere');
  78958. //due to the way oimo works with compounds, add 3 times
  78959. bodyConfig.size.push(size);
  78960. bodyConfig.size.push(size);
  78961. bodyConfig.size.push(size);
  78962. break;
  78963. case BABYLON.PhysicsImpostor.CylinderImpostor:
  78964. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  78965. var sizeY = checkWithEpsilon_1(extendSize.y);
  78966. bodyConfig.type.push('cylinder');
  78967. bodyConfig.size.push(sizeX);
  78968. bodyConfig.size.push(sizeY);
  78969. //due to the way oimo works with compounds, add one more value.
  78970. bodyConfig.size.push(sizeY);
  78971. break;
  78972. case BABYLON.PhysicsImpostor.PlaneImpostor:
  78973. case BABYLON.PhysicsImpostor.BoxImpostor:
  78974. default:
  78975. var sizeX = checkWithEpsilon_1(extendSize.x);
  78976. var sizeY = checkWithEpsilon_1(extendSize.y);
  78977. var sizeZ = checkWithEpsilon_1(extendSize.z);
  78978. bodyConfig.type.push('box');
  78979. bodyConfig.size.push(sizeX);
  78980. bodyConfig.size.push(sizeY);
  78981. bodyConfig.size.push(sizeZ);
  78982. break;
  78983. }
  78984. //actually not needed, but hey...
  78985. i.object.rotationQuaternion = oldQuaternion;
  78986. });
  78987. impostor.physicsBody = new this.BJSOIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  78988. }
  78989. else {
  78990. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  78991. }
  78992. impostor.setDeltaPosition(this._tmpPositionVector);
  78993. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  78994. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  78995. };
  78996. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  78997. //impostor.physicsBody.dispose();
  78998. //Same as : (older oimo versions)
  78999. this.world.removeRigidBody(impostor.physicsBody);
  79000. };
  79001. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  79002. var mainBody = impostorJoint.mainImpostor.physicsBody;
  79003. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  79004. if (!mainBody || !connectedBody) {
  79005. return;
  79006. }
  79007. var jointData = impostorJoint.joint.jointData;
  79008. var options = jointData.nativeParams || {};
  79009. var type;
  79010. var nativeJointData = {
  79011. body1: mainBody,
  79012. body2: connectedBody,
  79013. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  79014. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  79015. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  79016. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  79017. min: options.min,
  79018. max: options.max,
  79019. collision: options.collision || jointData.collision,
  79020. spring: options.spring,
  79021. //supporting older version of Oimo
  79022. world: this.world
  79023. };
  79024. switch (impostorJoint.joint.type) {
  79025. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  79026. type = "jointBall";
  79027. break;
  79028. case BABYLON.PhysicsJoint.SpringJoint:
  79029. BABYLON.Tools.Warn("this.BJSOIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  79030. var springData = jointData;
  79031. nativeJointData.min = springData.length || nativeJointData.min;
  79032. //Max should also be set, just make sure it is at least min
  79033. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  79034. case BABYLON.PhysicsJoint.DistanceJoint:
  79035. type = "jointDistance";
  79036. nativeJointData.max = jointData.maxDistance;
  79037. break;
  79038. case BABYLON.PhysicsJoint.PrismaticJoint:
  79039. type = "jointPrisme";
  79040. break;
  79041. case BABYLON.PhysicsJoint.SliderJoint:
  79042. type = "jointSlide";
  79043. break;
  79044. case BABYLON.PhysicsJoint.WheelJoint:
  79045. type = "jointWheel";
  79046. break;
  79047. case BABYLON.PhysicsJoint.HingeJoint:
  79048. default:
  79049. type = "jointHinge";
  79050. break;
  79051. }
  79052. nativeJointData.type = type;
  79053. impostorJoint.joint.physicsJoint = new this.BJSOIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  79054. };
  79055. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  79056. //Bug in Oimo prevents us from disposing a joint in the playground
  79057. //joint.joint.physicsJoint.dispose();
  79058. //So we will bruteforce it!
  79059. try {
  79060. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  79061. }
  79062. catch (e) {
  79063. BABYLON.Tools.Warn(e);
  79064. }
  79065. };
  79066. OimoJSPlugin.prototype.isSupported = function () {
  79067. return this.BJSOIMO !== undefined;
  79068. };
  79069. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  79070. if (!impostor.physicsBody.sleeping) {
  79071. //TODO check that
  79072. if (impostor.physicsBody.shapes.next) {
  79073. var parentShape = this._getLastShape(impostor.physicsBody);
  79074. impostor.object.position.x = parentShape.position.x * this.BJSOIMO.WORLD_SCALE;
  79075. impostor.object.position.y = parentShape.position.y * this.BJSOIMO.WORLD_SCALE;
  79076. impostor.object.position.z = parentShape.position.z * this.BJSOIMO.WORLD_SCALE;
  79077. }
  79078. else {
  79079. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  79080. }
  79081. if (impostor.object.rotationQuaternion) {
  79082. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  79083. impostor.object.rotationQuaternion.normalize();
  79084. }
  79085. }
  79086. };
  79087. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  79088. var body = impostor.physicsBody;
  79089. body.position.init(newPosition.x * this.BJSOIMO.INV_SCALE, newPosition.y * this.BJSOIMO.INV_SCALE, newPosition.z * this.BJSOIMO.INV_SCALE);
  79090. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  79091. body.syncShapes();
  79092. body.awake();
  79093. };
  79094. OimoJSPlugin.prototype._getLastShape = function (body) {
  79095. var lastShape = body.shapes;
  79096. while (lastShape.next) {
  79097. lastShape = lastShape.next;
  79098. }
  79099. return lastShape;
  79100. };
  79101. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  79102. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  79103. };
  79104. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  79105. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  79106. };
  79107. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  79108. var v = impostor.physicsBody.linearVelocity;
  79109. if (!v) {
  79110. return null;
  79111. }
  79112. return new BABYLON.Vector3(v.x, v.y, v.z);
  79113. };
  79114. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  79115. var v = impostor.physicsBody.angularVelocity;
  79116. if (!v) {
  79117. return null;
  79118. }
  79119. return new BABYLON.Vector3(v.x, v.y, v.z);
  79120. };
  79121. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  79122. var staticBody = mass === 0;
  79123. //this will actually set the body's density and not its mass.
  79124. //But this is how oimo treats the mass variable.
  79125. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  79126. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  79127. };
  79128. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  79129. return impostor.physicsBody.shapes.density;
  79130. };
  79131. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  79132. return impostor.physicsBody.shapes.friction;
  79133. };
  79134. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  79135. impostor.physicsBody.shapes.friction = friction;
  79136. };
  79137. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  79138. return impostor.physicsBody.shapes.restitution;
  79139. };
  79140. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  79141. impostor.physicsBody.shapes.restitution = restitution;
  79142. };
  79143. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  79144. impostor.physicsBody.sleep();
  79145. };
  79146. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  79147. impostor.physicsBody.awake();
  79148. };
  79149. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  79150. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  79151. if (minDistance !== void 0) {
  79152. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  79153. }
  79154. };
  79155. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  79156. //TODO separate rotational and transational motors.
  79157. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  79158. if (motor) {
  79159. motor.setMotor(speed, maxForce);
  79160. }
  79161. };
  79162. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  79163. //TODO separate rotational and transational motors.
  79164. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  79165. if (motor) {
  79166. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  79167. }
  79168. };
  79169. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  79170. var body = impostor.physicsBody;
  79171. mesh.position.x = body.position.x;
  79172. mesh.position.y = body.position.y;
  79173. mesh.position.z = body.position.z;
  79174. if (mesh.rotationQuaternion) {
  79175. mesh.rotationQuaternion.x = body.orientation.x;
  79176. mesh.rotationQuaternion.y = body.orientation.y;
  79177. mesh.rotationQuaternion.z = body.orientation.z;
  79178. mesh.rotationQuaternion.w = body.orientation.s;
  79179. }
  79180. };
  79181. OimoJSPlugin.prototype.getRadius = function (impostor) {
  79182. return impostor.physicsBody.shapes.radius;
  79183. };
  79184. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  79185. var shape = impostor.physicsBody.shapes;
  79186. result.x = shape.halfWidth * 2;
  79187. result.y = shape.halfHeight * 2;
  79188. result.z = shape.halfDepth * 2;
  79189. };
  79190. OimoJSPlugin.prototype.dispose = function () {
  79191. this.world.clear();
  79192. };
  79193. return OimoJSPlugin;
  79194. }());
  79195. BABYLON.OimoJSPlugin = OimoJSPlugin;
  79196. })(BABYLON || (BABYLON = {}));
  79197. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  79198. "use strict";
  79199. var BABYLON;
  79200. (function (BABYLON) {
  79201. /*
  79202. * Based on jsTGALoader - Javascript loader for TGA file
  79203. * By Vincent Thibault
  79204. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  79205. */
  79206. var TGATools = /** @class */ (function () {
  79207. function TGATools() {
  79208. }
  79209. TGATools.GetTGAHeader = function (data) {
  79210. var offset = 0;
  79211. var header = {
  79212. id_length: data[offset++],
  79213. colormap_type: data[offset++],
  79214. image_type: data[offset++],
  79215. colormap_index: data[offset++] | data[offset++] << 8,
  79216. colormap_length: data[offset++] | data[offset++] << 8,
  79217. colormap_size: data[offset++],
  79218. origin: [
  79219. data[offset++] | data[offset++] << 8,
  79220. data[offset++] | data[offset++] << 8
  79221. ],
  79222. width: data[offset++] | data[offset++] << 8,
  79223. height: data[offset++] | data[offset++] << 8,
  79224. pixel_size: data[offset++],
  79225. flags: data[offset++]
  79226. };
  79227. return header;
  79228. };
  79229. TGATools.UploadContent = function (gl, data) {
  79230. // Not enough data to contain header ?
  79231. if (data.length < 19) {
  79232. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  79233. return;
  79234. }
  79235. // Read Header
  79236. var offset = 18;
  79237. var header = TGATools.GetTGAHeader(data);
  79238. // Assume it's a valid Targa file.
  79239. if (header.id_length + offset > data.length) {
  79240. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  79241. return;
  79242. }
  79243. // Skip not needed data
  79244. offset += header.id_length;
  79245. var use_rle = false;
  79246. var use_pal = false;
  79247. var use_grey = false;
  79248. // Get some informations.
  79249. switch (header.image_type) {
  79250. case TGATools._TYPE_RLE_INDEXED:
  79251. use_rle = true;
  79252. case TGATools._TYPE_INDEXED:
  79253. use_pal = true;
  79254. break;
  79255. case TGATools._TYPE_RLE_RGB:
  79256. use_rle = true;
  79257. case TGATools._TYPE_RGB:
  79258. // use_rgb = true;
  79259. break;
  79260. case TGATools._TYPE_RLE_GREY:
  79261. use_rle = true;
  79262. case TGATools._TYPE_GREY:
  79263. use_grey = true;
  79264. break;
  79265. }
  79266. var pixel_data;
  79267. // var numAlphaBits = header.flags & 0xf;
  79268. var pixel_size = header.pixel_size >> 3;
  79269. var pixel_total = header.width * header.height * pixel_size;
  79270. // Read palettes
  79271. var palettes;
  79272. if (use_pal) {
  79273. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  79274. }
  79275. // Read LRE
  79276. if (use_rle) {
  79277. pixel_data = new Uint8Array(pixel_total);
  79278. var c, count, i;
  79279. var localOffset = 0;
  79280. var pixels = new Uint8Array(pixel_size);
  79281. while (offset < pixel_total && localOffset < pixel_total) {
  79282. c = data[offset++];
  79283. count = (c & 0x7f) + 1;
  79284. // RLE pixels
  79285. if (c & 0x80) {
  79286. // Bind pixel tmp array
  79287. for (i = 0; i < pixel_size; ++i) {
  79288. pixels[i] = data[offset++];
  79289. }
  79290. // Copy pixel array
  79291. for (i = 0; i < count; ++i) {
  79292. pixel_data.set(pixels, localOffset + i * pixel_size);
  79293. }
  79294. localOffset += pixel_size * count;
  79295. }
  79296. else {
  79297. count *= pixel_size;
  79298. for (i = 0; i < count; ++i) {
  79299. pixel_data[localOffset + i] = data[offset++];
  79300. }
  79301. localOffset += count;
  79302. }
  79303. }
  79304. }
  79305. else {
  79306. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  79307. }
  79308. // Load to texture
  79309. var x_start, y_start, x_step, y_step, y_end, x_end;
  79310. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  79311. default:
  79312. case TGATools._ORIGIN_UL:
  79313. x_start = 0;
  79314. x_step = 1;
  79315. x_end = header.width;
  79316. y_start = 0;
  79317. y_step = 1;
  79318. y_end = header.height;
  79319. break;
  79320. case TGATools._ORIGIN_BL:
  79321. x_start = 0;
  79322. x_step = 1;
  79323. x_end = header.width;
  79324. y_start = header.height - 1;
  79325. y_step = -1;
  79326. y_end = -1;
  79327. break;
  79328. case TGATools._ORIGIN_UR:
  79329. x_start = header.width - 1;
  79330. x_step = -1;
  79331. x_end = -1;
  79332. y_start = 0;
  79333. y_step = 1;
  79334. y_end = header.height;
  79335. break;
  79336. case TGATools._ORIGIN_BR:
  79337. x_start = header.width - 1;
  79338. x_step = -1;
  79339. x_end = -1;
  79340. y_start = header.height - 1;
  79341. y_step = -1;
  79342. y_end = -1;
  79343. break;
  79344. }
  79345. // Load the specify method
  79346. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  79347. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  79348. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  79349. };
  79350. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79351. var image = pixel_data, colormap = palettes;
  79352. var width = header.width, height = header.height;
  79353. var color, i = 0, x, y;
  79354. var imageData = new Uint8Array(width * height * 4);
  79355. for (y = y_start; y !== y_end; y += y_step) {
  79356. for (x = x_start; x !== x_end; x += x_step, i++) {
  79357. color = image[i];
  79358. imageData[(x + width * y) * 4 + 3] = 255;
  79359. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  79360. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  79361. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  79362. }
  79363. }
  79364. return imageData;
  79365. };
  79366. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79367. var image = pixel_data;
  79368. var width = header.width, height = header.height;
  79369. var color, i = 0, x, y;
  79370. var imageData = new Uint8Array(width * height * 4);
  79371. for (y = y_start; y !== y_end; y += y_step) {
  79372. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  79373. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  79374. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  79375. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  79376. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  79377. imageData[(x + width * y) * 4 + 0] = r;
  79378. imageData[(x + width * y) * 4 + 1] = g;
  79379. imageData[(x + width * y) * 4 + 2] = b;
  79380. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  79381. }
  79382. }
  79383. return imageData;
  79384. };
  79385. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79386. var image = pixel_data;
  79387. var width = header.width, height = header.height;
  79388. var i = 0, x, y;
  79389. var imageData = new Uint8Array(width * height * 4);
  79390. for (y = y_start; y !== y_end; y += y_step) {
  79391. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  79392. imageData[(x + width * y) * 4 + 3] = 255;
  79393. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  79394. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  79395. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  79396. }
  79397. }
  79398. return imageData;
  79399. };
  79400. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79401. var image = pixel_data;
  79402. var width = header.width, height = header.height;
  79403. var i = 0, x, y;
  79404. var imageData = new Uint8Array(width * height * 4);
  79405. for (y = y_start; y !== y_end; y += y_step) {
  79406. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  79407. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  79408. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  79409. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  79410. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  79411. }
  79412. }
  79413. return imageData;
  79414. };
  79415. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79416. var image = pixel_data;
  79417. var width = header.width, height = header.height;
  79418. var color, i = 0, x, y;
  79419. var imageData = new Uint8Array(width * height * 4);
  79420. for (y = y_start; y !== y_end; y += y_step) {
  79421. for (x = x_start; x !== x_end; x += x_step, i++) {
  79422. color = image[i];
  79423. imageData[(x + width * y) * 4 + 0] = color;
  79424. imageData[(x + width * y) * 4 + 1] = color;
  79425. imageData[(x + width * y) * 4 + 2] = color;
  79426. imageData[(x + width * y) * 4 + 3] = 255;
  79427. }
  79428. }
  79429. return imageData;
  79430. };
  79431. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  79432. var image = pixel_data;
  79433. var width = header.width, height = header.height;
  79434. var i = 0, x, y;
  79435. var imageData = new Uint8Array(width * height * 4);
  79436. for (y = y_start; y !== y_end; y += y_step) {
  79437. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  79438. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  79439. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  79440. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  79441. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  79442. }
  79443. }
  79444. return imageData;
  79445. };
  79446. //private static _TYPE_NO_DATA = 0;
  79447. TGATools._TYPE_INDEXED = 1;
  79448. TGATools._TYPE_RGB = 2;
  79449. TGATools._TYPE_GREY = 3;
  79450. TGATools._TYPE_RLE_INDEXED = 9;
  79451. TGATools._TYPE_RLE_RGB = 10;
  79452. TGATools._TYPE_RLE_GREY = 11;
  79453. TGATools._ORIGIN_MASK = 0x30;
  79454. TGATools._ORIGIN_SHIFT = 0x04;
  79455. TGATools._ORIGIN_BL = 0x00;
  79456. TGATools._ORIGIN_BR = 0x01;
  79457. TGATools._ORIGIN_UL = 0x02;
  79458. TGATools._ORIGIN_UR = 0x03;
  79459. return TGATools;
  79460. }());
  79461. BABYLON.TGATools = TGATools;
  79462. })(BABYLON || (BABYLON = {}));
  79463. //# sourceMappingURL=babylon.tga.js.map
  79464. "use strict";
  79465. var BABYLON;
  79466. (function (BABYLON) {
  79467. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  79468. // All values and structures referenced from:
  79469. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  79470. var DDS_MAGIC = 0x20534444;
  79471. var
  79472. //DDSD_CAPS = 0x1,
  79473. //DDSD_HEIGHT = 0x2,
  79474. //DDSD_WIDTH = 0x4,
  79475. //DDSD_PITCH = 0x8,
  79476. //DDSD_PIXELFORMAT = 0x1000,
  79477. DDSD_MIPMAPCOUNT = 0x20000;
  79478. //DDSD_LINEARSIZE = 0x80000,
  79479. //DDSD_DEPTH = 0x800000;
  79480. // var DDSCAPS_COMPLEX = 0x8,
  79481. // DDSCAPS_MIPMAP = 0x400000,
  79482. // DDSCAPS_TEXTURE = 0x1000;
  79483. var DDSCAPS2_CUBEMAP = 0x200;
  79484. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  79485. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  79486. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  79487. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  79488. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  79489. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  79490. // DDSCAPS2_VOLUME = 0x200000;
  79491. var
  79492. //DDPF_ALPHAPIXELS = 0x1,
  79493. //DDPF_ALPHA = 0x2,
  79494. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  79495. //DDPF_YUV = 0x200,
  79496. DDPF_LUMINANCE = 0x20000;
  79497. function FourCCToInt32(value) {
  79498. return value.charCodeAt(0) +
  79499. (value.charCodeAt(1) << 8) +
  79500. (value.charCodeAt(2) << 16) +
  79501. (value.charCodeAt(3) << 24);
  79502. }
  79503. function Int32ToFourCC(value) {
  79504. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  79505. }
  79506. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  79507. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  79508. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  79509. var FOURCC_DX10 = FourCCToInt32("DX10");
  79510. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  79511. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  79512. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  79513. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  79514. var headerLengthInt = 31; // The header length in 32 bit ints
  79515. // Offsets into the header array
  79516. var off_magic = 0;
  79517. var off_size = 1;
  79518. var off_flags = 2;
  79519. var off_height = 3;
  79520. var off_width = 4;
  79521. var off_mipmapCount = 7;
  79522. var off_pfFlags = 20;
  79523. var off_pfFourCC = 21;
  79524. var off_RGBbpp = 22;
  79525. var off_RMask = 23;
  79526. var off_GMask = 24;
  79527. var off_BMask = 25;
  79528. var off_AMask = 26;
  79529. // var off_caps1 = 27;
  79530. var off_caps2 = 28;
  79531. // var off_caps3 = 29;
  79532. // var off_caps4 = 30;
  79533. var off_dxgiFormat = 32;
  79534. ;
  79535. var DDSTools = /** @class */ (function () {
  79536. function DDSTools() {
  79537. }
  79538. DDSTools.GetDDSInfo = function (arrayBuffer) {
  79539. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  79540. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  79541. var mipmapCount = 1;
  79542. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  79543. mipmapCount = Math.max(1, header[off_mipmapCount]);
  79544. }
  79545. var fourCC = header[off_pfFourCC];
  79546. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  79547. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  79548. switch (fourCC) {
  79549. case FOURCC_D3DFMT_R16G16B16A16F:
  79550. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  79551. break;
  79552. case FOURCC_D3DFMT_R32G32B32A32F:
  79553. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  79554. break;
  79555. case FOURCC_DX10:
  79556. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  79557. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  79558. break;
  79559. }
  79560. }
  79561. return {
  79562. width: header[off_width],
  79563. height: header[off_height],
  79564. mipmapCount: mipmapCount,
  79565. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  79566. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  79567. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  79568. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  79569. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  79570. dxgiFormat: dxgiFormat,
  79571. textureType: textureType
  79572. };
  79573. };
  79574. DDSTools._ToHalfFloat = function (value) {
  79575. if (!DDSTools._FloatView) {
  79576. DDSTools._FloatView = new Float32Array(1);
  79577. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  79578. }
  79579. DDSTools._FloatView[0] = value;
  79580. var x = DDSTools._Int32View[0];
  79581. var bits = (x >> 16) & 0x8000; /* Get the sign */
  79582. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  79583. var e = (x >> 23) & 0xff; /* Using int is faster here */
  79584. /* If zero, or denormal, or exponent underflows too much for a denormal
  79585. * half, return signed zero. */
  79586. if (e < 103) {
  79587. return bits;
  79588. }
  79589. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  79590. if (e > 142) {
  79591. bits |= 0x7c00;
  79592. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  79593. * not Inf, so make sure we set one mantissa bit too. */
  79594. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  79595. return bits;
  79596. }
  79597. /* If exponent underflows but not too much, return a denormal */
  79598. if (e < 113) {
  79599. m |= 0x0800;
  79600. /* Extra rounding may overflow and set mantissa to 0 and exponent
  79601. * to 1, which is OK. */
  79602. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  79603. return bits;
  79604. }
  79605. bits |= ((e - 112) << 10) | (m >> 1);
  79606. bits += m & 1;
  79607. return bits;
  79608. };
  79609. DDSTools._FromHalfFloat = function (value) {
  79610. var s = (value & 0x8000) >> 15;
  79611. var e = (value & 0x7C00) >> 10;
  79612. var f = value & 0x03FF;
  79613. if (e === 0) {
  79614. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  79615. }
  79616. else if (e == 0x1F) {
  79617. return f ? NaN : ((s ? -1 : 1) * Infinity);
  79618. }
  79619. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  79620. };
  79621. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  79622. var destArray = new Float32Array(dataLength);
  79623. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  79624. var index = 0;
  79625. for (var y = 0; y < height; y++) {
  79626. for (var x = 0; x < width; x++) {
  79627. var srcPos = (x + y * width) * 4;
  79628. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  79629. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  79630. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  79631. if (DDSTools.StoreLODInAlphaChannel) {
  79632. destArray[index + 3] = lod;
  79633. }
  79634. else {
  79635. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  79636. }
  79637. index += 4;
  79638. }
  79639. }
  79640. return destArray;
  79641. };
  79642. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  79643. if (DDSTools.StoreLODInAlphaChannel) {
  79644. var destArray = new Uint16Array(dataLength);
  79645. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  79646. var index = 0;
  79647. for (var y = 0; y < height; y++) {
  79648. for (var x = 0; x < width; x++) {
  79649. var srcPos = (x + y * width) * 4;
  79650. destArray[index] = srcData[srcPos];
  79651. destArray[index + 1] = srcData[srcPos + 1];
  79652. destArray[index + 2] = srcData[srcPos + 2];
  79653. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  79654. index += 4;
  79655. }
  79656. }
  79657. return destArray;
  79658. }
  79659. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  79660. };
  79661. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  79662. if (DDSTools.StoreLODInAlphaChannel) {
  79663. var destArray = new Float32Array(dataLength);
  79664. var srcData = new Float32Array(arrayBuffer, dataOffset);
  79665. var index = 0;
  79666. for (var y = 0; y < height; y++) {
  79667. for (var x = 0; x < width; x++) {
  79668. var srcPos = (x + y * width) * 4;
  79669. destArray[index] = srcData[srcPos];
  79670. destArray[index + 1] = srcData[srcPos + 1];
  79671. destArray[index + 2] = srcData[srcPos + 2];
  79672. destArray[index + 3] = lod;
  79673. index += 4;
  79674. }
  79675. }
  79676. return destArray;
  79677. }
  79678. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  79679. };
  79680. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  79681. var destArray = new Uint8Array(dataLength);
  79682. var srcData = new Float32Array(arrayBuffer, dataOffset);
  79683. var index = 0;
  79684. for (var y = 0; y < height; y++) {
  79685. for (var x = 0; x < width; x++) {
  79686. var srcPos = (x + y * width) * 4;
  79687. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  79688. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  79689. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  79690. if (DDSTools.StoreLODInAlphaChannel) {
  79691. destArray[index + 3] = lod;
  79692. }
  79693. else {
  79694. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  79695. }
  79696. index += 4;
  79697. }
  79698. }
  79699. return destArray;
  79700. };
  79701. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  79702. var destArray = new Uint8Array(dataLength);
  79703. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  79704. var index = 0;
  79705. for (var y = 0; y < height; y++) {
  79706. for (var x = 0; x < width; x++) {
  79707. var srcPos = (x + y * width) * 4;
  79708. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  79709. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  79710. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  79711. if (DDSTools.StoreLODInAlphaChannel) {
  79712. destArray[index + 3] = lod;
  79713. }
  79714. else {
  79715. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  79716. }
  79717. index += 4;
  79718. }
  79719. }
  79720. return destArray;
  79721. };
  79722. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  79723. var byteArray = new Uint8Array(dataLength);
  79724. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  79725. var index = 0;
  79726. for (var y = 0; y < height; y++) {
  79727. for (var x = 0; x < width; x++) {
  79728. var srcPos = (x + y * width) * 4;
  79729. byteArray[index] = srcData[srcPos + rOffset];
  79730. byteArray[index + 1] = srcData[srcPos + gOffset];
  79731. byteArray[index + 2] = srcData[srcPos + bOffset];
  79732. byteArray[index + 3] = srcData[srcPos + aOffset];
  79733. index += 4;
  79734. }
  79735. }
  79736. return byteArray;
  79737. };
  79738. DDSTools._ExtractLongWordOrder = function (value) {
  79739. if (value === 0 || value === 255 || value === -16777216) {
  79740. return 0;
  79741. }
  79742. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  79743. };
  79744. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  79745. var byteArray = new Uint8Array(dataLength);
  79746. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  79747. var index = 0;
  79748. for (var y = 0; y < height; y++) {
  79749. for (var x = 0; x < width; x++) {
  79750. var srcPos = (x + y * width) * 3;
  79751. byteArray[index] = srcData[srcPos + rOffset];
  79752. byteArray[index + 1] = srcData[srcPos + gOffset];
  79753. byteArray[index + 2] = srcData[srcPos + bOffset];
  79754. index += 3;
  79755. }
  79756. }
  79757. return byteArray;
  79758. };
  79759. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  79760. var byteArray = new Uint8Array(dataLength);
  79761. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  79762. var index = 0;
  79763. for (var y = 0; y < height; y++) {
  79764. for (var x = 0; x < width; x++) {
  79765. var srcPos = (x + y * width);
  79766. byteArray[index] = srcData[srcPos];
  79767. index++;
  79768. }
  79769. }
  79770. return byteArray;
  79771. };
  79772. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  79773. if (lodIndex === void 0) { lodIndex = -1; }
  79774. var ext = engine.getCaps().s3tc;
  79775. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  79776. var fourCC, width, height, dataLength = 0, dataOffset;
  79777. var byteArray, mipmapCount, mip;
  79778. var internalFormat = 0;
  79779. var format = 0;
  79780. var blockBytes = 1;
  79781. if (header[off_magic] !== DDS_MAGIC) {
  79782. BABYLON.Tools.Error("Invalid magic number in DDS header");
  79783. return;
  79784. }
  79785. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  79786. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  79787. return;
  79788. }
  79789. if (info.isCompressed && !ext) {
  79790. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  79791. return;
  79792. }
  79793. var bpp = header[off_RGBbpp];
  79794. dataOffset = header[off_size] + 4;
  79795. var computeFormats = false;
  79796. if (info.isFourCC) {
  79797. fourCC = header[off_pfFourCC];
  79798. switch (fourCC) {
  79799. case FOURCC_DXT1:
  79800. blockBytes = 8;
  79801. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  79802. break;
  79803. case FOURCC_DXT3:
  79804. blockBytes = 16;
  79805. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  79806. break;
  79807. case FOURCC_DXT5:
  79808. blockBytes = 16;
  79809. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  79810. break;
  79811. case FOURCC_D3DFMT_R16G16B16A16F:
  79812. computeFormats = true;
  79813. break;
  79814. case FOURCC_D3DFMT_R32G32B32A32F:
  79815. computeFormats = true;
  79816. break;
  79817. case FOURCC_DX10:
  79818. // There is an additionnal header so dataOffset need to be changed
  79819. dataOffset += 5 * 4; // 5 uints
  79820. var supported = false;
  79821. switch (info.dxgiFormat) {
  79822. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  79823. computeFormats = true;
  79824. supported = true;
  79825. break;
  79826. case DXGI_FORMAT_B8G8R8X8_UNORM:
  79827. info.isRGB = true;
  79828. info.isFourCC = false;
  79829. bpp = 32;
  79830. supported = true;
  79831. break;
  79832. }
  79833. if (supported) {
  79834. break;
  79835. }
  79836. default:
  79837. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  79838. return;
  79839. }
  79840. }
  79841. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  79842. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  79843. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  79844. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  79845. if (computeFormats) {
  79846. format = engine._getWebGLTextureType(info.textureType);
  79847. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  79848. }
  79849. mipmapCount = 1;
  79850. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  79851. mipmapCount = Math.max(1, header[off_mipmapCount]);
  79852. }
  79853. for (var face = 0; face < faces; face++) {
  79854. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  79855. width = header[off_width];
  79856. height = header[off_height];
  79857. for (mip = 0; mip < mipmapCount; ++mip) {
  79858. if (lodIndex === -1 || lodIndex === mip) {
  79859. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  79860. var i = (lodIndex === -1) ? mip : 0;
  79861. if (!info.isCompressed && info.isFourCC) {
  79862. dataLength = width * height * 4;
  79863. var floatArray = null;
  79864. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  79865. if (bpp === 128) {
  79866. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79867. }
  79868. else if (bpp === 64) {
  79869. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79870. }
  79871. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  79872. format = engine._getWebGLTextureType(info.textureType);
  79873. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  79874. }
  79875. else {
  79876. if (bpp === 128) {
  79877. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79878. }
  79879. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  79880. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79881. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  79882. format = engine._getWebGLTextureType(info.textureType);
  79883. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  79884. }
  79885. else {
  79886. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  79887. }
  79888. }
  79889. if (floatArray) {
  79890. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  79891. }
  79892. }
  79893. else if (info.isRGB) {
  79894. if (bpp === 24) {
  79895. dataLength = width * height * 3;
  79896. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  79897. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  79898. }
  79899. else {
  79900. dataLength = width * height * 4;
  79901. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  79902. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  79903. }
  79904. }
  79905. else if (info.isLuminance) {
  79906. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  79907. var unpaddedRowSize = width;
  79908. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  79909. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  79910. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  79911. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  79912. }
  79913. else {
  79914. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  79915. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  79916. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  79917. }
  79918. }
  79919. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  79920. width *= 0.5;
  79921. height *= 0.5;
  79922. width = Math.max(1.0, width);
  79923. height = Math.max(1.0, height);
  79924. }
  79925. if (currentFace !== undefined) {
  79926. // Loading a single face
  79927. break;
  79928. }
  79929. }
  79930. };
  79931. DDSTools.StoreLODInAlphaChannel = false;
  79932. return DDSTools;
  79933. }());
  79934. BABYLON.DDSTools = DDSTools;
  79935. })(BABYLON || (BABYLON = {}));
  79936. //# sourceMappingURL=babylon.dds.js.map
  79937. "use strict";
  79938. var BABYLON;
  79939. (function (BABYLON) {
  79940. /**
  79941. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  79942. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  79943. */
  79944. var KhronosTextureContainer = /** @class */ (function () {
  79945. /**
  79946. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  79947. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  79948. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  79949. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  79950. */
  79951. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  79952. this.arrayBuffer = arrayBuffer;
  79953. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  79954. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  79955. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  79956. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  79957. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  79958. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  79959. BABYLON.Tools.Error("texture missing KTX identifier");
  79960. return;
  79961. }
  79962. // load the reset of the header in native 32 bit int
  79963. var header = new Int32Array(this.arrayBuffer, 12, 13);
  79964. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  79965. var oppositeEndianess = header[0] === 0x01020304;
  79966. // read all the header elements in order they exist in the file, without modification (sans endainness)
  79967. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  79968. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  79969. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  79970. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  79971. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  79972. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  79973. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  79974. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  79975. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  79976. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  79977. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  79978. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  79979. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  79980. if (this.glType !== 0) {
  79981. BABYLON.Tools.Error("only compressed formats currently supported");
  79982. return;
  79983. }
  79984. else {
  79985. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  79986. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  79987. }
  79988. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  79989. BABYLON.Tools.Error("only 2D textures currently supported");
  79990. return;
  79991. }
  79992. if (this.numberOfArrayElements !== 0) {
  79993. BABYLON.Tools.Error("texture arrays not currently supported");
  79994. return;
  79995. }
  79996. if (this.numberOfFaces !== facesExpected) {
  79997. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  79998. return;
  79999. }
  80000. // we now have a completely validated file, so could use existence of loadType as success
  80001. // would need to make this more elaborate & adjust checks above to support more than one load type
  80002. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  80003. }
  80004. // not as fast hardware based, but will probably never need to use
  80005. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  80006. return ((val & 0xFF) << 24)
  80007. | ((val & 0xFF00) << 8)
  80008. | ((val >> 8) & 0xFF00)
  80009. | ((val >> 24) & 0xFF);
  80010. };
  80011. /**
  80012. * It is assumed that the texture has already been created & is currently bound
  80013. */
  80014. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  80015. switch (this.loadType) {
  80016. case KhronosTextureContainer.COMPRESSED_2D:
  80017. this._upload2DCompressedLevels(gl, loadMipmaps);
  80018. break;
  80019. case KhronosTextureContainer.TEX_2D:
  80020. case KhronosTextureContainer.COMPRESSED_3D:
  80021. case KhronosTextureContainer.TEX_3D:
  80022. }
  80023. };
  80024. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  80025. // initialize width & height for level 1
  80026. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  80027. var width = this.pixelWidth;
  80028. var height = this.pixelHeight;
  80029. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  80030. for (var level = 0; level < mipmapCount; level++) {
  80031. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  80032. for (var face = 0; face < this.numberOfFaces; face++) {
  80033. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  80034. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  80035. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  80036. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  80037. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  80038. }
  80039. width = Math.max(1.0, width * 0.5);
  80040. height = Math.max(1.0, height * 0.5);
  80041. }
  80042. };
  80043. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  80044. // load types
  80045. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  80046. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  80047. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  80048. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  80049. return KhronosTextureContainer;
  80050. }());
  80051. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  80052. })(BABYLON || (BABYLON = {}));
  80053. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  80054. "use strict";
  80055. var BABYLON;
  80056. (function (BABYLON) {
  80057. var Debug = /** @class */ (function () {
  80058. function Debug() {
  80059. }
  80060. Debug.AxesViewer = /** @class */ (function () {
  80061. function AxesViewer(scene, scaleLines) {
  80062. if (scaleLines === void 0) { scaleLines = 1; }
  80063. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80064. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80065. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80066. this.scaleLines = 1;
  80067. this.scaleLines = scaleLines;
  80068. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  80069. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  80070. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  80071. this._xmesh.renderingGroupId = 2;
  80072. this._ymesh.renderingGroupId = 2;
  80073. this._zmesh.renderingGroupId = 2;
  80074. this._xmesh.material.checkReadyOnlyOnce = true;
  80075. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  80076. this._ymesh.material.checkReadyOnlyOnce = true;
  80077. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  80078. this._zmesh.material.checkReadyOnlyOnce = true;
  80079. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  80080. this.scene = scene;
  80081. }
  80082. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  80083. var scaleLines = this.scaleLines;
  80084. if (this._xmesh) {
  80085. this._xmesh.position.copyFrom(position);
  80086. }
  80087. if (this._ymesh) {
  80088. this._ymesh.position.copyFrom(position);
  80089. }
  80090. if (this._zmesh) {
  80091. this._zmesh.position.copyFrom(position);
  80092. }
  80093. var point2 = this._xline[1];
  80094. point2.x = xaxis.x * scaleLines;
  80095. point2.y = xaxis.y * scaleLines;
  80096. point2.z = xaxis.z * scaleLines;
  80097. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  80098. point2 = this._yline[1];
  80099. point2.x = yaxis.x * scaleLines;
  80100. point2.y = yaxis.y * scaleLines;
  80101. point2.z = yaxis.z * scaleLines;
  80102. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  80103. point2 = this._zline[1];
  80104. point2.x = zaxis.x * scaleLines;
  80105. point2.y = zaxis.y * scaleLines;
  80106. point2.z = zaxis.z * scaleLines;
  80107. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  80108. };
  80109. AxesViewer.prototype.dispose = function () {
  80110. if (this._xmesh) {
  80111. this._xmesh.dispose();
  80112. }
  80113. if (this._ymesh) {
  80114. this._ymesh.dispose();
  80115. }
  80116. if (this._zmesh) {
  80117. this._zmesh.dispose();
  80118. }
  80119. this._xmesh = null;
  80120. this._ymesh = null;
  80121. this._zmesh = null;
  80122. this.scene = null;
  80123. };
  80124. return AxesViewer;
  80125. }());
  80126. Debug.BoneAxesViewer = /** @class */ (function (_super) {
  80127. __extends(BoneAxesViewer, _super);
  80128. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  80129. if (scaleLines === void 0) { scaleLines = 1; }
  80130. var _this = _super.call(this, scene, scaleLines) || this;
  80131. _this.pos = BABYLON.Vector3.Zero();
  80132. _this.xaxis = BABYLON.Vector3.Zero();
  80133. _this.yaxis = BABYLON.Vector3.Zero();
  80134. _this.zaxis = BABYLON.Vector3.Zero();
  80135. _this.mesh = mesh;
  80136. _this.bone = bone;
  80137. return _this;
  80138. }
  80139. BoneAxesViewer.prototype.update = function () {
  80140. if (!this.mesh || !this.bone) {
  80141. return;
  80142. }
  80143. var bone = this.bone;
  80144. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  80145. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  80146. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  80147. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  80148. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  80149. };
  80150. BoneAxesViewer.prototype.dispose = function () {
  80151. if (this.mesh) {
  80152. this.mesh = null;
  80153. this.bone = null;
  80154. _super.prototype.dispose.call(this);
  80155. }
  80156. };
  80157. return BoneAxesViewer;
  80158. }(Debug.AxesViewer));
  80159. Debug.PhysicsViewer = /** @class */ (function () {
  80160. function PhysicsViewer(scene) {
  80161. this._impostors = [];
  80162. this._meshes = [];
  80163. this._numMeshes = 0;
  80164. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  80165. var physicEngine = this._scene.getPhysicsEngine();
  80166. if (physicEngine) {
  80167. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  80168. }
  80169. }
  80170. PhysicsViewer.prototype._updateDebugMeshes = function () {
  80171. var plugin = this._physicsEnginePlugin;
  80172. for (var i = 0; i < this._numMeshes; i++) {
  80173. var impostor = this._impostors[i];
  80174. if (!impostor) {
  80175. continue;
  80176. }
  80177. if (impostor.isDisposed) {
  80178. this.hideImpostor(this._impostors[i--]);
  80179. }
  80180. else {
  80181. var mesh = this._meshes[i];
  80182. if (mesh && plugin) {
  80183. plugin.syncMeshWithImpostor(mesh, impostor);
  80184. }
  80185. }
  80186. }
  80187. };
  80188. PhysicsViewer.prototype.showImpostor = function (impostor) {
  80189. if (!this._scene) {
  80190. return;
  80191. }
  80192. for (var i = 0; i < this._numMeshes; i++) {
  80193. if (this._impostors[i] == impostor) {
  80194. return;
  80195. }
  80196. }
  80197. var debugMesh = this._getDebugMesh(impostor, this._scene);
  80198. if (debugMesh) {
  80199. this._impostors[this._numMeshes] = impostor;
  80200. this._meshes[this._numMeshes] = debugMesh;
  80201. if (this._numMeshes === 0) {
  80202. this._renderFunction = this._updateDebugMeshes.bind(this);
  80203. this._scene.registerBeforeRender(this._renderFunction);
  80204. }
  80205. this._numMeshes++;
  80206. }
  80207. };
  80208. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  80209. if (!impostor || !this._scene) {
  80210. return;
  80211. }
  80212. var removed = false;
  80213. for (var i = 0; i < this._numMeshes; i++) {
  80214. if (this._impostors[i] == impostor) {
  80215. var mesh = this._meshes[i];
  80216. if (!mesh) {
  80217. continue;
  80218. }
  80219. this._scene.removeMesh(mesh);
  80220. mesh.dispose();
  80221. this._numMeshes--;
  80222. if (this._numMeshes > 0) {
  80223. this._meshes[i] = this._meshes[this._numMeshes];
  80224. this._impostors[i] = this._impostors[this._numMeshes];
  80225. this._meshes[this._numMeshes] = null;
  80226. this._impostors[this._numMeshes] = null;
  80227. }
  80228. else {
  80229. this._meshes[0] = null;
  80230. this._impostors[0] = null;
  80231. }
  80232. removed = true;
  80233. break;
  80234. }
  80235. }
  80236. if (removed && this._numMeshes === 0) {
  80237. this._scene.unregisterBeforeRender(this._renderFunction);
  80238. }
  80239. };
  80240. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  80241. if (!this._debugMaterial) {
  80242. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  80243. this._debugMaterial.wireframe = true;
  80244. }
  80245. return this._debugMaterial;
  80246. };
  80247. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  80248. if (!this._debugBoxMesh) {
  80249. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  80250. this._debugBoxMesh.renderingGroupId = 1;
  80251. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  80252. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  80253. scene.removeMesh(this._debugBoxMesh);
  80254. }
  80255. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  80256. };
  80257. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  80258. if (!this._debugSphereMesh) {
  80259. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  80260. this._debugSphereMesh.renderingGroupId = 1;
  80261. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  80262. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  80263. scene.removeMesh(this._debugSphereMesh);
  80264. }
  80265. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  80266. };
  80267. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  80268. var mesh = null;
  80269. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  80270. mesh = this._getDebugBoxMesh(scene);
  80271. impostor.getBoxSizeToRef(mesh.scaling);
  80272. }
  80273. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  80274. mesh = this._getDebugSphereMesh(scene);
  80275. var radius = impostor.getRadius();
  80276. mesh.scaling.x = radius * 2;
  80277. mesh.scaling.y = radius * 2;
  80278. mesh.scaling.z = radius * 2;
  80279. }
  80280. return mesh;
  80281. };
  80282. PhysicsViewer.prototype.dispose = function () {
  80283. for (var i = 0; i < this._numMeshes; i++) {
  80284. this.hideImpostor(this._impostors[i]);
  80285. }
  80286. if (this._debugBoxMesh) {
  80287. this._debugBoxMesh.dispose();
  80288. }
  80289. if (this._debugSphereMesh) {
  80290. this._debugSphereMesh.dispose();
  80291. }
  80292. if (this._debugMaterial) {
  80293. this._debugMaterial.dispose();
  80294. }
  80295. this._impostors.length = 0;
  80296. this._scene = null;
  80297. this._physicsEnginePlugin = null;
  80298. };
  80299. return PhysicsViewer;
  80300. }());
  80301. Debug.SkeletonViewer = /** @class */ (function () {
  80302. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  80303. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  80304. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  80305. this.skeleton = skeleton;
  80306. this.mesh = mesh;
  80307. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  80308. this.renderingGroupId = renderingGroupId;
  80309. this.color = BABYLON.Color3.White();
  80310. this._debugLines = new Array();
  80311. this._isEnabled = false;
  80312. this._scene = scene;
  80313. this.update();
  80314. this._renderFunction = this.update.bind(this);
  80315. }
  80316. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  80317. get: function () {
  80318. return this._isEnabled;
  80319. },
  80320. set: function (value) {
  80321. if (this._isEnabled === value) {
  80322. return;
  80323. }
  80324. this._isEnabled = value;
  80325. if (value) {
  80326. this._scene.registerBeforeRender(this._renderFunction);
  80327. }
  80328. else {
  80329. this._scene.unregisterBeforeRender(this._renderFunction);
  80330. }
  80331. },
  80332. enumerable: true,
  80333. configurable: true
  80334. });
  80335. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  80336. if (x === void 0) { x = 0; }
  80337. if (y === void 0) { y = 0; }
  80338. if (z === void 0) { z = 0; }
  80339. var tmat = BABYLON.Tmp.Matrix[0];
  80340. var parentBone = bone.getParent();
  80341. tmat.copyFrom(bone.getLocalMatrix());
  80342. if (x !== 0 || y !== 0 || z !== 0) {
  80343. var tmat2 = BABYLON.Tmp.Matrix[1];
  80344. BABYLON.Matrix.IdentityToRef(tmat2);
  80345. tmat2.m[12] = x;
  80346. tmat2.m[13] = y;
  80347. tmat2.m[14] = z;
  80348. tmat2.multiplyToRef(tmat, tmat);
  80349. }
  80350. if (parentBone) {
  80351. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  80352. }
  80353. tmat.multiplyToRef(meshMat, tmat);
  80354. position.x = tmat.m[12];
  80355. position.y = tmat.m[13];
  80356. position.z = tmat.m[14];
  80357. };
  80358. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  80359. var len = bones.length;
  80360. var meshPos = this.mesh.position;
  80361. for (var i = 0; i < len; i++) {
  80362. var bone = bones[i];
  80363. var points = this._debugLines[i];
  80364. if (!points) {
  80365. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80366. this._debugLines[i] = points;
  80367. }
  80368. this._getBonePosition(points[0], bone, meshMat);
  80369. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  80370. points[0].subtractInPlace(meshPos);
  80371. points[1].subtractInPlace(meshPos);
  80372. }
  80373. };
  80374. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  80375. var len = bones.length;
  80376. var boneNum = 0;
  80377. var meshPos = this.mesh.position;
  80378. for (var i = len - 1; i >= 0; i--) {
  80379. var childBone = bones[i];
  80380. var parentBone = childBone.getParent();
  80381. if (!parentBone) {
  80382. continue;
  80383. }
  80384. var points = this._debugLines[boneNum];
  80385. if (!points) {
  80386. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80387. this._debugLines[boneNum] = points;
  80388. }
  80389. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  80390. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  80391. points[0].subtractInPlace(meshPos);
  80392. points[1].subtractInPlace(meshPos);
  80393. boneNum++;
  80394. }
  80395. };
  80396. SkeletonViewer.prototype.update = function () {
  80397. if (this.autoUpdateBonesMatrices) {
  80398. this.skeleton.computeAbsoluteTransforms();
  80399. }
  80400. if (this.skeleton.bones[0].length === undefined) {
  80401. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  80402. }
  80403. else {
  80404. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  80405. }
  80406. if (!this._debugMesh) {
  80407. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  80408. this._debugMesh.renderingGroupId = this.renderingGroupId;
  80409. }
  80410. else {
  80411. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  80412. }
  80413. this._debugMesh.position.copyFrom(this.mesh.position);
  80414. this._debugMesh.color = this.color;
  80415. };
  80416. SkeletonViewer.prototype.dispose = function () {
  80417. if (this._debugMesh) {
  80418. this.isEnabled = false;
  80419. this._debugMesh.dispose();
  80420. this._debugMesh = null;
  80421. }
  80422. };
  80423. return SkeletonViewer;
  80424. }());
  80425. return Debug;
  80426. }());
  80427. BABYLON.Debug = Debug;
  80428. })(BABYLON || (BABYLON = {}));
  80429. //# sourceMappingURL=babylon.debugModules.js.map
  80430. "use strict";
  80431. var BABYLON;
  80432. (function (BABYLON) {
  80433. var RayHelper = /** @class */ (function () {
  80434. function RayHelper(ray) {
  80435. this.ray = ray;
  80436. }
  80437. RayHelper.CreateAndShow = function (ray, scene, color) {
  80438. var helper = new RayHelper(ray);
  80439. helper.show(scene, color);
  80440. return helper;
  80441. };
  80442. RayHelper.prototype.show = function (scene, color) {
  80443. if (!this._renderFunction && this.ray) {
  80444. var ray = this.ray;
  80445. this._renderFunction = this._render.bind(this);
  80446. this._scene = scene;
  80447. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  80448. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  80449. if (this._renderFunction) {
  80450. this._scene.registerBeforeRender(this._renderFunction);
  80451. }
  80452. }
  80453. if (color && this._renderLine) {
  80454. this._renderLine.color.copyFrom(color);
  80455. }
  80456. };
  80457. RayHelper.prototype.hide = function () {
  80458. if (this._renderFunction && this._scene) {
  80459. this._scene.unregisterBeforeRender(this._renderFunction);
  80460. this._scene = null;
  80461. this._renderFunction = null;
  80462. if (this._renderLine) {
  80463. this._renderLine.dispose();
  80464. this._renderLine = null;
  80465. }
  80466. this._renderPoints = [];
  80467. }
  80468. };
  80469. RayHelper.prototype._render = function () {
  80470. var ray = this.ray;
  80471. if (!ray) {
  80472. return;
  80473. }
  80474. var point = this._renderPoints[1];
  80475. var len = Math.min(ray.length, 1000000);
  80476. point.copyFrom(ray.direction);
  80477. point.scaleInPlace(len);
  80478. point.addInPlace(ray.origin);
  80479. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  80480. };
  80481. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  80482. this._attachedToMesh = mesh;
  80483. var ray = this.ray;
  80484. if (!ray) {
  80485. return;
  80486. }
  80487. if (!ray.direction) {
  80488. ray.direction = BABYLON.Vector3.Zero();
  80489. }
  80490. if (!ray.origin) {
  80491. ray.origin = BABYLON.Vector3.Zero();
  80492. }
  80493. if (length) {
  80494. ray.length = length;
  80495. }
  80496. if (!meshSpaceOrigin) {
  80497. meshSpaceOrigin = BABYLON.Vector3.Zero();
  80498. }
  80499. if (!meshSpaceDirection) {
  80500. // -1 so that this will work with Mesh.lookAt
  80501. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  80502. }
  80503. if (!this._meshSpaceDirection) {
  80504. this._meshSpaceDirection = meshSpaceDirection.clone();
  80505. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  80506. }
  80507. else {
  80508. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  80509. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  80510. }
  80511. if (!this._updateToMeshFunction) {
  80512. this._updateToMeshFunction = this._updateToMesh.bind(this);
  80513. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  80514. }
  80515. this._updateToMesh();
  80516. };
  80517. RayHelper.prototype.detachFromMesh = function () {
  80518. if (this._attachedToMesh) {
  80519. if (this._updateToMeshFunction) {
  80520. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  80521. }
  80522. this._attachedToMesh = null;
  80523. this._updateToMeshFunction = null;
  80524. }
  80525. };
  80526. RayHelper.prototype._updateToMesh = function () {
  80527. var ray = this.ray;
  80528. if (!this._attachedToMesh || !ray) {
  80529. return;
  80530. }
  80531. if (this._attachedToMesh._isDisposed) {
  80532. this.detachFromMesh();
  80533. return;
  80534. }
  80535. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  80536. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  80537. };
  80538. RayHelper.prototype.dispose = function () {
  80539. this.hide();
  80540. this.detachFromMesh();
  80541. this.ray = null;
  80542. };
  80543. return RayHelper;
  80544. }());
  80545. BABYLON.RayHelper = RayHelper;
  80546. })(BABYLON || (BABYLON = {}));
  80547. //# sourceMappingURL=babylon.rayHelper.js.map
  80548. "use strict";
  80549. var BABYLON;
  80550. (function (BABYLON) {
  80551. // load the inspector using require, if not present in the global namespace.
  80552. var DebugLayer = /** @class */ (function () {
  80553. function DebugLayer(scene) {
  80554. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  80555. this._scene = scene;
  80556. // load inspector using require, if it doesn't exist on the global namespace.
  80557. }
  80558. /** Creates the inspector window. */
  80559. DebugLayer.prototype._createInspector = function (config) {
  80560. if (config === void 0) { config = {}; }
  80561. var popup = config.popup || false;
  80562. var initialTab = config.initialTab || 0;
  80563. var parentElement = config.parentElement || null;
  80564. if (!this._inspector) {
  80565. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  80566. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  80567. } // else nothing to do,; instance is already existing
  80568. };
  80569. DebugLayer.prototype.isVisible = function () {
  80570. if (!this._inspector) {
  80571. return false;
  80572. }
  80573. return true;
  80574. };
  80575. DebugLayer.prototype.hide = function () {
  80576. if (this._inspector) {
  80577. try {
  80578. this._inspector.dispose();
  80579. }
  80580. catch (e) {
  80581. // If the inspector has been removed directly from the inspector tool
  80582. }
  80583. this._inspector = null;
  80584. }
  80585. };
  80586. DebugLayer.prototype.show = function (config) {
  80587. if (config === void 0) { config = {}; }
  80588. if (typeof this.BJSINSPECTOR == 'undefined') {
  80589. // Load inspector and add it to the DOM
  80590. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  80591. }
  80592. else {
  80593. // Otherwise creates the inspector
  80594. this._createInspector(config);
  80595. }
  80596. };
  80597. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  80598. return DebugLayer;
  80599. }());
  80600. BABYLON.DebugLayer = DebugLayer;
  80601. })(BABYLON || (BABYLON = {}));
  80602. //# sourceMappingURL=babylon.debugLayer.js.map
  80603. "use strict";
  80604. var BABYLON;
  80605. (function (BABYLON) {
  80606. var BoundingBoxRenderer = /** @class */ (function () {
  80607. function BoundingBoxRenderer(scene) {
  80608. this.frontColor = new BABYLON.Color3(1, 1, 1);
  80609. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  80610. this.showBackLines = true;
  80611. this.renderList = new BABYLON.SmartArray(32);
  80612. this._vertexBuffers = {};
  80613. this._scene = scene;
  80614. }
  80615. BoundingBoxRenderer.prototype._prepareRessources = function () {
  80616. if (this._colorShader) {
  80617. return;
  80618. }
  80619. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  80620. attributes: [BABYLON.VertexBuffer.PositionKind],
  80621. uniforms: ["world", "viewProjection", "color"]
  80622. });
  80623. var engine = this._scene.getEngine();
  80624. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  80625. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  80626. this._createIndexBuffer();
  80627. };
  80628. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  80629. var engine = this._scene.getEngine();
  80630. 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]);
  80631. };
  80632. BoundingBoxRenderer.prototype._rebuild = function () {
  80633. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  80634. if (vb) {
  80635. vb._rebuild();
  80636. }
  80637. this._createIndexBuffer();
  80638. };
  80639. BoundingBoxRenderer.prototype.reset = function () {
  80640. this.renderList.reset();
  80641. };
  80642. BoundingBoxRenderer.prototype.render = function () {
  80643. if (this.renderList.length === 0) {
  80644. return;
  80645. }
  80646. this._prepareRessources();
  80647. if (!this._colorShader.isReady()) {
  80648. return;
  80649. }
  80650. var engine = this._scene.getEngine();
  80651. engine.setDepthWrite(false);
  80652. this._colorShader._preBind();
  80653. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  80654. var boundingBox = this.renderList.data[boundingBoxIndex];
  80655. var min = boundingBox.minimum;
  80656. var max = boundingBox.maximum;
  80657. var diff = max.subtract(min);
  80658. var median = min.add(diff.scale(0.5));
  80659. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  80660. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  80661. .multiply(boundingBox.getWorldMatrix());
  80662. // VBOs
  80663. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  80664. if (this.showBackLines) {
  80665. // Back
  80666. engine.setDepthFunctionToGreaterOrEqual();
  80667. this._scene.resetCachedMaterial();
  80668. this._colorShader.setColor4("color", this.backColor.toColor4());
  80669. this._colorShader.bind(worldMatrix);
  80670. // Draw order
  80671. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  80672. }
  80673. // Front
  80674. engine.setDepthFunctionToLess();
  80675. this._scene.resetCachedMaterial();
  80676. this._colorShader.setColor4("color", this.frontColor.toColor4());
  80677. this._colorShader.bind(worldMatrix);
  80678. // Draw order
  80679. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  80680. }
  80681. this._colorShader.unbind();
  80682. engine.setDepthFunctionToLessOrEqual();
  80683. engine.setDepthWrite(true);
  80684. };
  80685. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  80686. this._prepareRessources();
  80687. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  80688. return;
  80689. }
  80690. var engine = this._scene.getEngine();
  80691. engine.setDepthWrite(false);
  80692. engine.setColorWrite(false);
  80693. this._colorShader._preBind();
  80694. var boundingBox = mesh._boundingInfo.boundingBox;
  80695. var min = boundingBox.minimum;
  80696. var max = boundingBox.maximum;
  80697. var diff = max.subtract(min);
  80698. var median = min.add(diff.scale(0.5));
  80699. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  80700. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  80701. .multiply(boundingBox.getWorldMatrix());
  80702. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  80703. engine.setDepthFunctionToLess();
  80704. this._scene.resetCachedMaterial();
  80705. this._colorShader.bind(worldMatrix);
  80706. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  80707. this._colorShader.unbind();
  80708. engine.setDepthFunctionToLessOrEqual();
  80709. engine.setDepthWrite(true);
  80710. engine.setColorWrite(true);
  80711. };
  80712. BoundingBoxRenderer.prototype.dispose = function () {
  80713. if (!this._colorShader) {
  80714. return;
  80715. }
  80716. this.renderList.dispose();
  80717. this._colorShader.dispose();
  80718. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  80719. if (buffer) {
  80720. buffer.dispose();
  80721. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  80722. }
  80723. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  80724. };
  80725. return BoundingBoxRenderer;
  80726. }());
  80727. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  80728. })(BABYLON || (BABYLON = {}));
  80729. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  80730. "use strict";
  80731. var BABYLON;
  80732. (function (BABYLON) {
  80733. var MorphTarget = /** @class */ (function () {
  80734. function MorphTarget(name, influence) {
  80735. if (influence === void 0) { influence = 0; }
  80736. this.name = name;
  80737. this.animations = new Array();
  80738. this._positions = null;
  80739. this._normals = null;
  80740. this._tangents = null;
  80741. this.onInfluenceChanged = new BABYLON.Observable();
  80742. this.influence = influence;
  80743. }
  80744. Object.defineProperty(MorphTarget.prototype, "influence", {
  80745. get: function () {
  80746. return this._influence;
  80747. },
  80748. set: function (influence) {
  80749. if (this._influence === influence) {
  80750. return;
  80751. }
  80752. var previous = this._influence;
  80753. this._influence = influence;
  80754. if (this.onInfluenceChanged.hasObservers) {
  80755. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  80756. }
  80757. },
  80758. enumerable: true,
  80759. configurable: true
  80760. });
  80761. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  80762. get: function () {
  80763. return !!this._positions;
  80764. },
  80765. enumerable: true,
  80766. configurable: true
  80767. });
  80768. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  80769. get: function () {
  80770. return !!this._normals;
  80771. },
  80772. enumerable: true,
  80773. configurable: true
  80774. });
  80775. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  80776. get: function () {
  80777. return !!this._tangents;
  80778. },
  80779. enumerable: true,
  80780. configurable: true
  80781. });
  80782. MorphTarget.prototype.setPositions = function (data) {
  80783. this._positions = data;
  80784. };
  80785. MorphTarget.prototype.getPositions = function () {
  80786. return this._positions;
  80787. };
  80788. MorphTarget.prototype.setNormals = function (data) {
  80789. this._normals = data;
  80790. };
  80791. MorphTarget.prototype.getNormals = function () {
  80792. return this._normals;
  80793. };
  80794. MorphTarget.prototype.setTangents = function (data) {
  80795. this._tangents = data;
  80796. };
  80797. MorphTarget.prototype.getTangents = function () {
  80798. return this._tangents;
  80799. };
  80800. /**
  80801. * Serializes the current target into a Serialization object.
  80802. * Returns the serialized object.
  80803. */
  80804. MorphTarget.prototype.serialize = function () {
  80805. var serializationObject = {};
  80806. serializationObject.name = this.name;
  80807. serializationObject.influence = this.influence;
  80808. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  80809. if (this.hasNormals) {
  80810. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  80811. }
  80812. if (this.hasTangents) {
  80813. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  80814. }
  80815. // Animations
  80816. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  80817. return serializationObject;
  80818. };
  80819. // Statics
  80820. MorphTarget.Parse = function (serializationObject) {
  80821. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  80822. result.setPositions(serializationObject.positions);
  80823. if (serializationObject.normals) {
  80824. result.setNormals(serializationObject.normals);
  80825. }
  80826. if (serializationObject.tangents) {
  80827. result.setTangents(serializationObject.tangents);
  80828. }
  80829. // Animations
  80830. if (serializationObject.animations) {
  80831. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  80832. var parsedAnimation = serializationObject.animations[animationIndex];
  80833. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  80834. }
  80835. }
  80836. return result;
  80837. };
  80838. MorphTarget.FromMesh = function (mesh, name, influence) {
  80839. if (!name) {
  80840. name = mesh.name;
  80841. }
  80842. var result = new MorphTarget(name, influence);
  80843. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  80844. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  80845. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  80846. }
  80847. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  80848. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  80849. }
  80850. return result;
  80851. };
  80852. return MorphTarget;
  80853. }());
  80854. BABYLON.MorphTarget = MorphTarget;
  80855. })(BABYLON || (BABYLON = {}));
  80856. //# sourceMappingURL=babylon.morphTarget.js.map
  80857. "use strict";
  80858. var BABYLON;
  80859. (function (BABYLON) {
  80860. var MorphTargetManager = /** @class */ (function () {
  80861. function MorphTargetManager(scene) {
  80862. if (scene === void 0) { scene = null; }
  80863. this._targets = new Array();
  80864. this._targetObservable = new Array();
  80865. this._activeTargets = new BABYLON.SmartArray(16);
  80866. this._supportsNormals = false;
  80867. this._supportsTangents = false;
  80868. this._vertexCount = 0;
  80869. this._uniqueId = 0;
  80870. this._tempInfluences = new Array();
  80871. if (!scene) {
  80872. scene = BABYLON.Engine.LastCreatedScene;
  80873. }
  80874. this._scene = scene;
  80875. if (this._scene) {
  80876. this._scene.morphTargetManagers.push(this);
  80877. this._uniqueId = this._scene.getUniqueId();
  80878. }
  80879. }
  80880. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  80881. get: function () {
  80882. return this._uniqueId;
  80883. },
  80884. enumerable: true,
  80885. configurable: true
  80886. });
  80887. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  80888. get: function () {
  80889. return this._vertexCount;
  80890. },
  80891. enumerable: true,
  80892. configurable: true
  80893. });
  80894. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  80895. get: function () {
  80896. return this._supportsNormals;
  80897. },
  80898. enumerable: true,
  80899. configurable: true
  80900. });
  80901. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  80902. get: function () {
  80903. return this._supportsTangents;
  80904. },
  80905. enumerable: true,
  80906. configurable: true
  80907. });
  80908. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  80909. get: function () {
  80910. return this._targets.length;
  80911. },
  80912. enumerable: true,
  80913. configurable: true
  80914. });
  80915. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  80916. get: function () {
  80917. return this._activeTargets.length;
  80918. },
  80919. enumerable: true,
  80920. configurable: true
  80921. });
  80922. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  80923. get: function () {
  80924. return this._influences;
  80925. },
  80926. enumerable: true,
  80927. configurable: true
  80928. });
  80929. MorphTargetManager.prototype.getActiveTarget = function (index) {
  80930. return this._activeTargets.data[index];
  80931. };
  80932. MorphTargetManager.prototype.getTarget = function (index) {
  80933. return this._targets[index];
  80934. };
  80935. MorphTargetManager.prototype.addTarget = function (target) {
  80936. var _this = this;
  80937. this._targets.push(target);
  80938. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  80939. _this._syncActiveTargets(needUpdate);
  80940. }));
  80941. this._syncActiveTargets(true);
  80942. };
  80943. MorphTargetManager.prototype.removeTarget = function (target) {
  80944. var index = this._targets.indexOf(target);
  80945. if (index >= 0) {
  80946. this._targets.splice(index, 1);
  80947. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  80948. this._syncActiveTargets(true);
  80949. }
  80950. };
  80951. /**
  80952. * Serializes the current manager into a Serialization object.
  80953. * Returns the serialized object.
  80954. */
  80955. MorphTargetManager.prototype.serialize = function () {
  80956. var serializationObject = {};
  80957. serializationObject.id = this.uniqueId;
  80958. serializationObject.targets = [];
  80959. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  80960. var target = _a[_i];
  80961. serializationObject.targets.push(target.serialize());
  80962. }
  80963. return serializationObject;
  80964. };
  80965. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  80966. var influenceCount = 0;
  80967. this._activeTargets.reset();
  80968. this._supportsNormals = true;
  80969. this._supportsTangents = true;
  80970. this._vertexCount = 0;
  80971. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  80972. var target = _a[_i];
  80973. this._activeTargets.push(target);
  80974. this._tempInfluences[influenceCount++] = target.influence;
  80975. var positions = target.getPositions();
  80976. if (positions) {
  80977. this._supportsNormals = this._supportsNormals && target.hasNormals;
  80978. this._supportsTangents = this._supportsTangents && target.hasTangents;
  80979. var vertexCount = positions.length / 3;
  80980. if (this._vertexCount === 0) {
  80981. this._vertexCount = vertexCount;
  80982. }
  80983. else if (this._vertexCount !== vertexCount) {
  80984. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  80985. return;
  80986. }
  80987. }
  80988. }
  80989. if (!this._influences || this._influences.length !== influenceCount) {
  80990. this._influences = new Float32Array(influenceCount);
  80991. }
  80992. for (var index = 0; index < influenceCount; index++) {
  80993. this._influences[index] = this._tempInfluences[index];
  80994. }
  80995. if (needUpdate && this._scene) {
  80996. // Flag meshes as dirty to resync with the active targets
  80997. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  80998. var mesh = _c[_b];
  80999. if (mesh.morphTargetManager === this) {
  81000. mesh._syncGeometryWithMorphTargetManager();
  81001. }
  81002. }
  81003. }
  81004. };
  81005. // Statics
  81006. MorphTargetManager.Parse = function (serializationObject, scene) {
  81007. var result = new MorphTargetManager(scene);
  81008. result._uniqueId = serializationObject.id;
  81009. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  81010. var targetData = _a[_i];
  81011. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  81012. }
  81013. return result;
  81014. };
  81015. return MorphTargetManager;
  81016. }());
  81017. BABYLON.MorphTargetManager = MorphTargetManager;
  81018. })(BABYLON || (BABYLON = {}));
  81019. //# sourceMappingURL=babylon.morphTargetManager.js.map
  81020. "use strict";
  81021. var BABYLON;
  81022. (function (BABYLON) {
  81023. var Octree = /** @class */ (function () {
  81024. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  81025. if (maxDepth === void 0) { maxDepth = 2; }
  81026. this.maxDepth = maxDepth;
  81027. this.dynamicContent = new Array();
  81028. this._maxBlockCapacity = maxBlockCapacity || 64;
  81029. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  81030. this._creationFunc = creationFunc;
  81031. }
  81032. // Methods
  81033. Octree.prototype.update = function (worldMin, worldMax, entries) {
  81034. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  81035. };
  81036. Octree.prototype.addMesh = function (entry) {
  81037. for (var index = 0; index < this.blocks.length; index++) {
  81038. var block = this.blocks[index];
  81039. block.addEntry(entry);
  81040. }
  81041. };
  81042. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  81043. this._selectionContent.reset();
  81044. for (var index = 0; index < this.blocks.length; index++) {
  81045. var block = this.blocks[index];
  81046. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  81047. }
  81048. if (allowDuplicate) {
  81049. this._selectionContent.concat(this.dynamicContent);
  81050. }
  81051. else {
  81052. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  81053. }
  81054. return this._selectionContent;
  81055. };
  81056. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  81057. this._selectionContent.reset();
  81058. for (var index = 0; index < this.blocks.length; index++) {
  81059. var block = this.blocks[index];
  81060. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  81061. }
  81062. if (allowDuplicate) {
  81063. this._selectionContent.concat(this.dynamicContent);
  81064. }
  81065. else {
  81066. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  81067. }
  81068. return this._selectionContent;
  81069. };
  81070. Octree.prototype.intersectsRay = function (ray) {
  81071. this._selectionContent.reset();
  81072. for (var index = 0; index < this.blocks.length; index++) {
  81073. var block = this.blocks[index];
  81074. block.intersectsRay(ray, this._selectionContent);
  81075. }
  81076. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  81077. return this._selectionContent;
  81078. };
  81079. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  81080. target.blocks = new Array();
  81081. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  81082. // Segmenting space
  81083. for (var x = 0; x < 2; x++) {
  81084. for (var y = 0; y < 2; y++) {
  81085. for (var z = 0; z < 2; z++) {
  81086. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  81087. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  81088. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  81089. block.addEntries(entries);
  81090. target.blocks.push(block);
  81091. }
  81092. }
  81093. }
  81094. };
  81095. Octree.CreationFuncForMeshes = function (entry, block) {
  81096. var boundingInfo = entry.getBoundingInfo();
  81097. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  81098. block.entries.push(entry);
  81099. }
  81100. };
  81101. Octree.CreationFuncForSubMeshes = function (entry, block) {
  81102. var boundingInfo = entry.getBoundingInfo();
  81103. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  81104. block.entries.push(entry);
  81105. }
  81106. };
  81107. return Octree;
  81108. }());
  81109. BABYLON.Octree = Octree;
  81110. })(BABYLON || (BABYLON = {}));
  81111. //# sourceMappingURL=babylon.octree.js.map
  81112. "use strict";
  81113. var BABYLON;
  81114. (function (BABYLON) {
  81115. var OctreeBlock = /** @class */ (function () {
  81116. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  81117. this.entries = new Array();
  81118. this._boundingVectors = new Array();
  81119. this._capacity = capacity;
  81120. this._depth = depth;
  81121. this._maxDepth = maxDepth;
  81122. this._creationFunc = creationFunc;
  81123. this._minPoint = minPoint;
  81124. this._maxPoint = maxPoint;
  81125. this._boundingVectors.push(minPoint.clone());
  81126. this._boundingVectors.push(maxPoint.clone());
  81127. this._boundingVectors.push(minPoint.clone());
  81128. this._boundingVectors[2].x = maxPoint.x;
  81129. this._boundingVectors.push(minPoint.clone());
  81130. this._boundingVectors[3].y = maxPoint.y;
  81131. this._boundingVectors.push(minPoint.clone());
  81132. this._boundingVectors[4].z = maxPoint.z;
  81133. this._boundingVectors.push(maxPoint.clone());
  81134. this._boundingVectors[5].z = minPoint.z;
  81135. this._boundingVectors.push(maxPoint.clone());
  81136. this._boundingVectors[6].x = minPoint.x;
  81137. this._boundingVectors.push(maxPoint.clone());
  81138. this._boundingVectors[7].y = minPoint.y;
  81139. }
  81140. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  81141. // Property
  81142. get: function () {
  81143. return this._capacity;
  81144. },
  81145. enumerable: true,
  81146. configurable: true
  81147. });
  81148. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  81149. get: function () {
  81150. return this._minPoint;
  81151. },
  81152. enumerable: true,
  81153. configurable: true
  81154. });
  81155. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  81156. get: function () {
  81157. return this._maxPoint;
  81158. },
  81159. enumerable: true,
  81160. configurable: true
  81161. });
  81162. // Methods
  81163. OctreeBlock.prototype.addEntry = function (entry) {
  81164. if (this.blocks) {
  81165. for (var index = 0; index < this.blocks.length; index++) {
  81166. var block = this.blocks[index];
  81167. block.addEntry(entry);
  81168. }
  81169. return;
  81170. }
  81171. this._creationFunc(entry, this);
  81172. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  81173. this.createInnerBlocks();
  81174. }
  81175. };
  81176. OctreeBlock.prototype.addEntries = function (entries) {
  81177. for (var index = 0; index < entries.length; index++) {
  81178. var mesh = entries[index];
  81179. this.addEntry(mesh);
  81180. }
  81181. };
  81182. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  81183. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  81184. if (this.blocks) {
  81185. for (var index = 0; index < this.blocks.length; index++) {
  81186. var block = this.blocks[index];
  81187. block.select(frustumPlanes, selection, allowDuplicate);
  81188. }
  81189. return;
  81190. }
  81191. if (allowDuplicate) {
  81192. selection.concat(this.entries);
  81193. }
  81194. else {
  81195. selection.concatWithNoDuplicate(this.entries);
  81196. }
  81197. }
  81198. };
  81199. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  81200. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  81201. if (this.blocks) {
  81202. for (var index = 0; index < this.blocks.length; index++) {
  81203. var block = this.blocks[index];
  81204. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  81205. }
  81206. return;
  81207. }
  81208. if (allowDuplicate) {
  81209. selection.concat(this.entries);
  81210. }
  81211. else {
  81212. selection.concatWithNoDuplicate(this.entries);
  81213. }
  81214. }
  81215. };
  81216. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  81217. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  81218. if (this.blocks) {
  81219. for (var index = 0; index < this.blocks.length; index++) {
  81220. var block = this.blocks[index];
  81221. block.intersectsRay(ray, selection);
  81222. }
  81223. return;
  81224. }
  81225. selection.concatWithNoDuplicate(this.entries);
  81226. }
  81227. };
  81228. OctreeBlock.prototype.createInnerBlocks = function () {
  81229. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  81230. };
  81231. return OctreeBlock;
  81232. }());
  81233. BABYLON.OctreeBlock = OctreeBlock;
  81234. })(BABYLON || (BABYLON = {}));
  81235. //# sourceMappingURL=babylon.octreeBlock.js.map
  81236. "use strict";
  81237. var BABYLON;
  81238. (function (BABYLON) {
  81239. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  81240. __extends(VRDistortionCorrectionPostProcess, _super);
  81241. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  81242. var _this = _super.call(this, name, "vrDistortionCorrection", [
  81243. 'LensCenter',
  81244. 'Scale',
  81245. 'ScaleIn',
  81246. 'HmdWarpParam'
  81247. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  81248. _this._isRightEye = isRightEye;
  81249. _this._distortionFactors = vrMetrics.distortionK;
  81250. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  81251. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  81252. _this.adaptScaleToCurrentViewport = true;
  81253. _this.onSizeChangedObservable.add(function () {
  81254. _this.aspectRatio = _this.width * .5 / _this.height;
  81255. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  81256. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  81257. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  81258. });
  81259. _this.onApplyObservable.add(function (effect) {
  81260. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  81261. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  81262. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  81263. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  81264. });
  81265. return _this;
  81266. }
  81267. return VRDistortionCorrectionPostProcess;
  81268. }(BABYLON.PostProcess));
  81269. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  81270. })(BABYLON || (BABYLON = {}));
  81271. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  81272. "use strict";
  81273. var BABYLON;
  81274. (function (BABYLON) {
  81275. var AnaglyphPostProcess = /** @class */ (function (_super) {
  81276. __extends(AnaglyphPostProcess, _super);
  81277. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  81278. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  81279. _this._passedProcess = rigCameras[0]._rigPostProcess;
  81280. _this.onApplyObservable.add(function (effect) {
  81281. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  81282. });
  81283. return _this;
  81284. }
  81285. return AnaglyphPostProcess;
  81286. }(BABYLON.PostProcess));
  81287. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  81288. })(BABYLON || (BABYLON = {}));
  81289. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  81290. "use strict";
  81291. var BABYLON;
  81292. (function (BABYLON) {
  81293. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  81294. __extends(StereoscopicInterlacePostProcess, _super);
  81295. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  81296. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  81297. _this._passedProcess = rigCameras[0]._rigPostProcess;
  81298. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  81299. _this.onSizeChangedObservable.add(function () {
  81300. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  81301. });
  81302. _this.onApplyObservable.add(function (effect) {
  81303. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  81304. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  81305. });
  81306. return _this;
  81307. }
  81308. return StereoscopicInterlacePostProcess;
  81309. }(BABYLON.PostProcess));
  81310. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  81311. })(BABYLON || (BABYLON = {}));
  81312. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  81313. "use strict";
  81314. var BABYLON;
  81315. (function (BABYLON) {
  81316. /**
  81317. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  81318. * Screen rotation is taken into account.
  81319. */
  81320. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  81321. function FreeCameraDeviceOrientationInput() {
  81322. var _this = this;
  81323. this._screenOrientationAngle = 0;
  81324. this._screenQuaternion = new BABYLON.Quaternion();
  81325. this._alpha = 0;
  81326. this._beta = 0;
  81327. this._gamma = 0;
  81328. this._orientationChanged = function () {
  81329. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  81330. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  81331. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  81332. };
  81333. this._deviceOrientation = function (evt) {
  81334. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  81335. _this._beta = evt.beta !== null ? evt.beta : 0;
  81336. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  81337. };
  81338. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  81339. this._orientationChanged();
  81340. }
  81341. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  81342. get: function () {
  81343. return this._camera;
  81344. },
  81345. set: function (camera) {
  81346. this._camera = camera;
  81347. if (this._camera != null && !this._camera.rotationQuaternion) {
  81348. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  81349. }
  81350. },
  81351. enumerable: true,
  81352. configurable: true
  81353. });
  81354. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  81355. window.addEventListener("orientationchange", this._orientationChanged);
  81356. window.addEventListener("deviceorientation", this._deviceOrientation);
  81357. //In certain cases, the attach control is called AFTER orientation was changed,
  81358. //So this is needed.
  81359. this._orientationChanged();
  81360. };
  81361. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  81362. window.removeEventListener("orientationchange", this._orientationChanged);
  81363. window.removeEventListener("deviceorientation", this._deviceOrientation);
  81364. };
  81365. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  81366. //if no device orientation provided, don't update the rotation.
  81367. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  81368. if (!this._alpha)
  81369. return;
  81370. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  81371. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  81372. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  81373. //Mirror on XY Plane
  81374. this._camera.rotationQuaternion.z *= -1;
  81375. this._camera.rotationQuaternion.w *= -1;
  81376. };
  81377. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  81378. return "FreeCameraDeviceOrientationInput";
  81379. };
  81380. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  81381. return "deviceOrientation";
  81382. };
  81383. return FreeCameraDeviceOrientationInput;
  81384. }());
  81385. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  81386. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  81387. })(BABYLON || (BABYLON = {}));
  81388. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  81389. "use strict";
  81390. var BABYLON;
  81391. (function (BABYLON) {
  81392. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  81393. function ArcRotateCameraVRDeviceOrientationInput() {
  81394. this.alphaCorrection = 1;
  81395. this.betaCorrection = 1;
  81396. this.gammaCorrection = 1;
  81397. this._alpha = 0;
  81398. this._gamma = 0;
  81399. this._dirty = false;
  81400. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  81401. }
  81402. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  81403. this.camera.attachControl(element, noPreventDefault);
  81404. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  81405. };
  81406. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  81407. if (evt.alpha !== null) {
  81408. this._alpha = +evt.alpha | 0;
  81409. }
  81410. if (evt.gamma !== null) {
  81411. this._gamma = +evt.gamma | 0;
  81412. }
  81413. this._dirty = true;
  81414. };
  81415. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  81416. if (this._dirty) {
  81417. this._dirty = false;
  81418. if (this._gamma < 0) {
  81419. this._gamma = 180 + this._gamma;
  81420. }
  81421. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  81422. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  81423. }
  81424. };
  81425. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  81426. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  81427. };
  81428. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  81429. return "ArcRotateCameraVRDeviceOrientationInput";
  81430. };
  81431. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  81432. return "VRDeviceOrientation";
  81433. };
  81434. return ArcRotateCameraVRDeviceOrientationInput;
  81435. }());
  81436. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  81437. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  81438. })(BABYLON || (BABYLON = {}));
  81439. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  81440. "use strict";
  81441. var BABYLON;
  81442. (function (BABYLON) {
  81443. var VRCameraMetrics = /** @class */ (function () {
  81444. function VRCameraMetrics() {
  81445. this.compensateDistortion = true;
  81446. }
  81447. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  81448. get: function () {
  81449. return this.hResolution / (2 * this.vResolution);
  81450. },
  81451. enumerable: true,
  81452. configurable: true
  81453. });
  81454. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  81455. get: function () {
  81456. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  81457. },
  81458. enumerable: true,
  81459. configurable: true
  81460. });
  81461. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  81462. get: function () {
  81463. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  81464. var h = (4 * meters) / this.hScreenSize;
  81465. return BABYLON.Matrix.Translation(h, 0, 0);
  81466. },
  81467. enumerable: true,
  81468. configurable: true
  81469. });
  81470. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  81471. get: function () {
  81472. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  81473. var h = (4 * meters) / this.hScreenSize;
  81474. return BABYLON.Matrix.Translation(-h, 0, 0);
  81475. },
  81476. enumerable: true,
  81477. configurable: true
  81478. });
  81479. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  81480. get: function () {
  81481. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  81482. },
  81483. enumerable: true,
  81484. configurable: true
  81485. });
  81486. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  81487. get: function () {
  81488. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  81489. },
  81490. enumerable: true,
  81491. configurable: true
  81492. });
  81493. VRCameraMetrics.GetDefault = function () {
  81494. var result = new VRCameraMetrics();
  81495. result.hResolution = 1280;
  81496. result.vResolution = 800;
  81497. result.hScreenSize = 0.149759993;
  81498. result.vScreenSize = 0.0935999975;
  81499. result.vScreenCenter = 0.0467999987;
  81500. result.eyeToScreenDistance = 0.0410000011;
  81501. result.lensSeparationDistance = 0.0635000020;
  81502. result.interpupillaryDistance = 0.0640000030;
  81503. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  81504. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  81505. result.postProcessScaleFactor = 1.714605507808412;
  81506. result.lensCenterOffset = 0.151976421;
  81507. return result;
  81508. };
  81509. return VRCameraMetrics;
  81510. }());
  81511. BABYLON.VRCameraMetrics = VRCameraMetrics;
  81512. })(BABYLON || (BABYLON = {}));
  81513. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  81514. "use strict";
  81515. var BABYLON;
  81516. (function (BABYLON) {
  81517. /**
  81518. * This represents a WebVR camera.
  81519. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  81520. * @example http://doc.babylonjs.com/how_to/webvr_camera
  81521. */
  81522. var WebVRFreeCamera = /** @class */ (function (_super) {
  81523. __extends(WebVRFreeCamera, _super);
  81524. /**
  81525. * Instantiates a WebVRFreeCamera.
  81526. * @param name The name of the WebVRFreeCamera
  81527. * @param position The starting anchor position for the camera
  81528. * @param scene The scene the camera belongs to
  81529. * @param webVROptions a set of customizable options for the webVRCamera
  81530. */
  81531. function WebVRFreeCamera(name, position, scene, webVROptions) {
  81532. if (webVROptions === void 0) { webVROptions = {}; }
  81533. var _this = _super.call(this, name, position, scene) || this;
  81534. _this.webVROptions = webVROptions;
  81535. /**
  81536. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  81537. */
  81538. _this._vrDevice = null;
  81539. /**
  81540. * The rawPose of the vrDevice.
  81541. */
  81542. _this.rawPose = null;
  81543. _this._specsVersion = "1.1";
  81544. _this._attached = false;
  81545. _this._descendants = [];
  81546. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  81547. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  81548. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  81549. _this._standingMatrix = null;
  81550. /**
  81551. * Represents device position in babylon space.
  81552. */
  81553. _this.devicePosition = BABYLON.Vector3.Zero();
  81554. /**
  81555. * Represents device rotation in babylon space.
  81556. */
  81557. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  81558. /**
  81559. * The scale of the device to be used when translating from device space to babylon space.
  81560. */
  81561. _this.deviceScaleFactor = 1;
  81562. _this._deviceToWorld = BABYLON.Matrix.Identity();
  81563. _this._worldToDevice = BABYLON.Matrix.Identity();
  81564. /**
  81565. * References to the webVR controllers for the vrDevice.
  81566. */
  81567. _this.controllers = [];
  81568. /**
  81569. * Emits an event when a controller is attached.
  81570. */
  81571. _this.onControllersAttachedObservable = new BABYLON.Observable();
  81572. /**
  81573. * Emits an event when a controller's mesh has been loaded;
  81574. */
  81575. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  81576. /**
  81577. * If the rig cameras be used as parent instead of this camera.
  81578. */
  81579. _this.rigParenting = true;
  81580. _this._defaultHeight = undefined;
  81581. _this._workingVector = BABYLON.Vector3.Zero();
  81582. _this._oneVector = BABYLON.Vector3.One();
  81583. _this._workingMatrix = BABYLON.Matrix.Identity();
  81584. _this._cache.position = BABYLON.Vector3.Zero();
  81585. if (webVROptions.defaultHeight) {
  81586. _this._defaultHeight = webVROptions.defaultHeight;
  81587. _this.position.y = _this._defaultHeight;
  81588. }
  81589. _this.minZ = 0.1;
  81590. //legacy support - the compensation boolean was removed.
  81591. if (arguments.length === 5) {
  81592. _this.webVROptions = arguments[4];
  81593. }
  81594. // default webVR options
  81595. if (_this.webVROptions.trackPosition == undefined) {
  81596. _this.webVROptions.trackPosition = true;
  81597. }
  81598. if (_this.webVROptions.controllerMeshes == undefined) {
  81599. _this.webVROptions.controllerMeshes = true;
  81600. }
  81601. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  81602. _this.webVROptions.defaultLightingOnControllers = true;
  81603. }
  81604. _this.rotationQuaternion = new BABYLON.Quaternion();
  81605. if (_this.webVROptions && _this.webVROptions.positionScale) {
  81606. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  81607. }
  81608. //enable VR
  81609. var engine = _this.getEngine();
  81610. _this._onVREnabled = function (success) { if (success) {
  81611. _this.initControllers();
  81612. } };
  81613. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  81614. engine.initWebVR().add(function (event) {
  81615. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  81616. return;
  81617. }
  81618. _this._vrDevice = event.vrDisplay;
  81619. //reset the rig parameters.
  81620. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  81621. if (_this._attached) {
  81622. _this.getEngine().enableVR();
  81623. }
  81624. });
  81625. if (typeof (VRFrameData) !== "undefined")
  81626. _this._frameData = new VRFrameData();
  81627. /**
  81628. * The idea behind the following lines:
  81629. * objects that have the camera as parent should actually have the rig cameras as a parent.
  81630. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  81631. * the second will not show it correctly.
  81632. *
  81633. * To solve this - each object that has the camera as parent will be added to a protected array.
  81634. * When the rig camera renders, it will take this array and set all of those to be its children.
  81635. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  81636. * Amazing!
  81637. */
  81638. scene.onBeforeCameraRenderObservable.add(function (camera) {
  81639. if (camera.parent === _this && _this.rigParenting) {
  81640. _this._descendants = _this.getDescendants(true, function (n) {
  81641. // don't take the cameras or the controllers!
  81642. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  81643. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  81644. return !isController && !isRigCamera;
  81645. });
  81646. _this._descendants.forEach(function (node) {
  81647. node.parent = camera;
  81648. });
  81649. }
  81650. });
  81651. scene.onAfterCameraRenderObservable.add(function (camera) {
  81652. if (camera.parent === _this && _this.rigParenting) {
  81653. _this._descendants.forEach(function (node) {
  81654. node.parent = _this;
  81655. });
  81656. }
  81657. });
  81658. return _this;
  81659. }
  81660. /**
  81661. * Gets the device distance from the ground in meters.
  81662. * @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.
  81663. */
  81664. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  81665. if (this._standingMatrix) {
  81666. // Add standing matrix offset to get real offset from ground in room
  81667. this._standingMatrix.getTranslationToRef(this._workingVector);
  81668. return this._deviceRoomPosition.y + this._workingVector.y;
  81669. }
  81670. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  81671. return this._defaultHeight || 0;
  81672. };
  81673. /**
  81674. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  81675. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  81676. */
  81677. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  81678. var _this = this;
  81679. if (callback === void 0) { callback = function (bool) { }; }
  81680. // Use standing matrix if available
  81681. this.getEngine().initWebVRAsync().then(function (result) {
  81682. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  81683. callback(false);
  81684. }
  81685. else {
  81686. _this._standingMatrix = new BABYLON.Matrix();
  81687. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  81688. if (!_this.getScene().useRightHandedSystem) {
  81689. [2, 6, 8, 9, 14].forEach(function (num) {
  81690. if (_this._standingMatrix) {
  81691. _this._standingMatrix.m[num] *= -1;
  81692. }
  81693. });
  81694. }
  81695. callback(true);
  81696. }
  81697. });
  81698. };
  81699. /**
  81700. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  81701. * @returns A promise with a boolean set to if the standing matrix is supported.
  81702. */
  81703. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  81704. var _this = this;
  81705. return new Promise(function (res, rej) {
  81706. _this.useStandingMatrix(function (supported) {
  81707. res(supported);
  81708. });
  81709. });
  81710. };
  81711. /**
  81712. * Disposes the camera
  81713. */
  81714. WebVRFreeCamera.prototype.dispose = function () {
  81715. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  81716. _super.prototype.dispose.call(this);
  81717. };
  81718. /**
  81719. * Gets a vrController by name.
  81720. * @param name The name of the controller to retreive
  81721. * @returns the controller matching the name specified or null if not found
  81722. */
  81723. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  81724. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  81725. var gp = _a[_i];
  81726. if (gp.hand === name) {
  81727. return gp;
  81728. }
  81729. }
  81730. return null;
  81731. };
  81732. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  81733. /**
  81734. * The controller corrisponding to the users left hand.
  81735. */
  81736. get: function () {
  81737. if (!this._leftController) {
  81738. this._leftController = this.getControllerByName("left");
  81739. }
  81740. return this._leftController;
  81741. },
  81742. enumerable: true,
  81743. configurable: true
  81744. });
  81745. ;
  81746. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  81747. /**
  81748. * The controller corrisponding to the users right hand.
  81749. */
  81750. get: function () {
  81751. if (!this._rightController) {
  81752. this._rightController = this.getControllerByName("right");
  81753. }
  81754. return this._rightController;
  81755. },
  81756. enumerable: true,
  81757. configurable: true
  81758. });
  81759. ;
  81760. /**
  81761. * Casts a ray forward from the vrCamera's gaze.
  81762. * @param length Length of the ray (default: 100)
  81763. * @returns the ray corrisponding to the gaze
  81764. */
  81765. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  81766. if (length === void 0) { length = 100; }
  81767. if (this.leftCamera) {
  81768. // Use left eye to avoid computation to compute center on every call
  81769. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  81770. }
  81771. else {
  81772. return _super.prototype.getForwardRay.call(this, length);
  81773. }
  81774. };
  81775. /**
  81776. * Updates the camera based on device's frame data
  81777. */
  81778. WebVRFreeCamera.prototype._checkInputs = function () {
  81779. if (this._vrDevice && this._vrDevice.isPresenting) {
  81780. this._vrDevice.getFrameData(this._frameData);
  81781. this.updateFromDevice(this._frameData.pose);
  81782. }
  81783. _super.prototype._checkInputs.call(this);
  81784. };
  81785. /**
  81786. * Updates the poseControlled values based on the input device pose.
  81787. * @param poseData Pose coming from the device
  81788. */
  81789. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  81790. if (poseData && poseData.orientation) {
  81791. this.rawPose = poseData;
  81792. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  81793. if (this.getScene().useRightHandedSystem) {
  81794. this._deviceRoomRotationQuaternion.z *= -1;
  81795. this._deviceRoomRotationQuaternion.w *= -1;
  81796. }
  81797. if (this.webVROptions.trackPosition && this.rawPose.position) {
  81798. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  81799. if (this.getScene().useRightHandedSystem) {
  81800. this._deviceRoomPosition.z *= -1;
  81801. }
  81802. }
  81803. }
  81804. };
  81805. /**
  81806. * WebVR's attach control will start broadcasting frames to the device.
  81807. * Note that in certain browsers (chrome for example) this function must be called
  81808. * within a user-interaction callback. Example:
  81809. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  81810. *
  81811. * @param element html element to attach the vrDevice to
  81812. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  81813. */
  81814. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  81815. _super.prototype.attachControl.call(this, element, noPreventDefault);
  81816. this._attached = true;
  81817. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  81818. if (this._vrDevice) {
  81819. this.getEngine().enableVR();
  81820. }
  81821. };
  81822. /**
  81823. * Detaches the camera from the html element and disables VR
  81824. *
  81825. * @param element html element to detach from
  81826. */
  81827. WebVRFreeCamera.prototype.detachControl = function (element) {
  81828. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  81829. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  81830. _super.prototype.detachControl.call(this, element);
  81831. this._attached = false;
  81832. this.getEngine().disableVR();
  81833. };
  81834. /**
  81835. * @returns the name of this class
  81836. */
  81837. WebVRFreeCamera.prototype.getClassName = function () {
  81838. return "WebVRFreeCamera";
  81839. };
  81840. /**
  81841. * Calls resetPose on the vrDisplay
  81842. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  81843. */
  81844. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  81845. //uses the vrDisplay's "resetPose()".
  81846. //pitch and roll won't be affected.
  81847. this._vrDevice.resetPose();
  81848. };
  81849. /**
  81850. * Updates the rig cameras (left and right eye)
  81851. */
  81852. WebVRFreeCamera.prototype._updateRigCameras = function () {
  81853. var camLeft = this._rigCameras[0];
  81854. var camRight = this._rigCameras[1];
  81855. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  81856. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  81857. camLeft.position.copyFrom(this._deviceRoomPosition);
  81858. camRight.position.copyFrom(this._deviceRoomPosition);
  81859. };
  81860. /**
  81861. * Updates the cached values of the camera
  81862. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  81863. */
  81864. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  81865. var _this = this;
  81866. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  81867. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  81868. if (!this.updateCacheCalled) {
  81869. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  81870. this.updateCacheCalled = true;
  81871. this.update();
  81872. }
  81873. // Set working vector to the device position in room space rotated by the new rotation
  81874. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  81875. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  81876. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  81877. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  81878. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  81879. // Add translation from anchor position
  81880. this._deviceToWorld.getTranslationToRef(this._workingVector);
  81881. this._workingVector.addInPlace(this.position);
  81882. this._workingVector.subtractInPlace(this._cache.position);
  81883. this._deviceToWorld.setTranslation(this._workingVector);
  81884. // Set an inverted matrix to be used when updating the camera
  81885. this._deviceToWorld.invertToRef(this._worldToDevice);
  81886. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  81887. this.controllers.forEach(function (controller) {
  81888. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  81889. controller.update();
  81890. });
  81891. }
  81892. if (!ignoreParentClass) {
  81893. _super.prototype._updateCache.call(this);
  81894. }
  81895. this.updateCacheCalled = false;
  81896. };
  81897. /**
  81898. * Updates the current device position and rotation in the babylon world
  81899. */
  81900. WebVRFreeCamera.prototype.update = function () {
  81901. // Get current device position in babylon world
  81902. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  81903. // Get current device rotation in babylon world
  81904. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  81905. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  81906. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  81907. _super.prototype.update.call(this);
  81908. };
  81909. /**
  81910. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  81911. * @returns an identity matrix
  81912. */
  81913. WebVRFreeCamera.prototype._getViewMatrix = function () {
  81914. return BABYLON.Matrix.Identity();
  81915. };
  81916. /**
  81917. * This function is called by the two RIG cameras.
  81918. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  81919. */
  81920. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  81921. var _this = this;
  81922. // Update the parent camera prior to using a child camera to avoid desynchronization
  81923. var parentCamera = this._cameraRigParams["parentCamera"];
  81924. parentCamera._updateCache();
  81925. //WebVR 1.1
  81926. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  81927. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  81928. if (!this.getScene().useRightHandedSystem) {
  81929. [2, 6, 8, 9, 14].forEach(function (num) {
  81930. _this._webvrViewMatrix.m[num] *= -1;
  81931. });
  81932. }
  81933. // update the camera rotation matrix
  81934. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  81935. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  81936. // Computing target and final matrix
  81937. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  81938. // should the view matrix be updated with scale and position offset?
  81939. if (parentCamera.deviceScaleFactor !== 1) {
  81940. this._webvrViewMatrix.invert();
  81941. // scale the position, if set
  81942. if (parentCamera.deviceScaleFactor) {
  81943. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  81944. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  81945. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  81946. }
  81947. this._webvrViewMatrix.invert();
  81948. }
  81949. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  81950. return this._webvrViewMatrix;
  81951. };
  81952. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  81953. var _this = this;
  81954. var parentCamera = this.parent;
  81955. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  81956. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  81957. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  81958. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  81959. //babylon compatible matrix
  81960. if (!this.getScene().useRightHandedSystem) {
  81961. [8, 9, 10, 11].forEach(function (num) {
  81962. _this._projectionMatrix.m[num] *= -1;
  81963. });
  81964. }
  81965. return this._projectionMatrix;
  81966. };
  81967. /**
  81968. * Initializes the controllers and their meshes
  81969. */
  81970. WebVRFreeCamera.prototype.initControllers = function () {
  81971. var _this = this;
  81972. this.controllers = [];
  81973. var manager = this.getScene().gamepadManager;
  81974. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  81975. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  81976. var webVrController = gamepad;
  81977. if (webVrController.defaultModel) {
  81978. webVrController.defaultModel.setEnabled(false);
  81979. }
  81980. if (webVrController.hand === "right") {
  81981. _this._rightController = null;
  81982. }
  81983. if (webVrController.hand === "left") {
  81984. _this._leftController = null;
  81985. }
  81986. var controllerIndex = _this.controllers.indexOf(webVrController);
  81987. if (controllerIndex !== -1) {
  81988. _this.controllers.splice(controllerIndex, 1);
  81989. }
  81990. }
  81991. });
  81992. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  81993. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  81994. var webVrController_1 = gamepad;
  81995. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  81996. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  81997. if (_this.webVROptions.controllerMeshes) {
  81998. if (webVrController_1.defaultModel) {
  81999. webVrController_1.defaultModel.setEnabled(true);
  82000. }
  82001. else {
  82002. // Load the meshes
  82003. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  82004. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  82005. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  82006. if (_this.webVROptions.defaultLightingOnControllers) {
  82007. if (!_this._lightOnControllers) {
  82008. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  82009. }
  82010. var activateLightOnSubMeshes_1 = function (mesh, light) {
  82011. var children = mesh.getChildren();
  82012. if (children.length !== 0) {
  82013. children.forEach(function (mesh) {
  82014. light.includedOnlyMeshes.push(mesh);
  82015. activateLightOnSubMeshes_1(mesh, light);
  82016. });
  82017. }
  82018. };
  82019. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  82020. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  82021. }
  82022. });
  82023. }
  82024. }
  82025. webVrController_1.attachToPoseControlledCamera(_this);
  82026. // since this is async - sanity check. Is the controller already stored?
  82027. if (_this.controllers.indexOf(webVrController_1) === -1) {
  82028. //add to the controllers array
  82029. _this.controllers.push(webVrController_1);
  82030. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  82031. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  82032. // So we're overriding setting left & right manually to be sure
  82033. var firstViveWandDetected = false;
  82034. for (var i = 0; i < _this.controllers.length; i++) {
  82035. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  82036. if (!firstViveWandDetected) {
  82037. firstViveWandDetected = true;
  82038. _this.controllers[i].hand = "left";
  82039. }
  82040. else {
  82041. _this.controllers[i].hand = "right";
  82042. }
  82043. }
  82044. }
  82045. //did we find enough controllers? Great! let the developer know.
  82046. if (_this.controllers.length >= 2) {
  82047. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  82048. }
  82049. }
  82050. }
  82051. });
  82052. };
  82053. return WebVRFreeCamera;
  82054. }(BABYLON.FreeCamera));
  82055. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  82056. })(BABYLON || (BABYLON = {}));
  82057. //# sourceMappingURL=babylon.webVRCamera.js.map
  82058. "use strict";
  82059. var BABYLON;
  82060. (function (BABYLON) {
  82061. // We're mainly based on the logic defined into the FreeCamera code
  82062. /**
  82063. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  82064. * being tilted forward or back and left or right.
  82065. */
  82066. var DeviceOrientationCamera = /** @class */ (function (_super) {
  82067. __extends(DeviceOrientationCamera, _super);
  82068. /**
  82069. * Creates a new device orientation camera. @see DeviceOrientationCamera
  82070. * @param name The name of the camera
  82071. * @param position The start position camera
  82072. * @param scene The scene the camera belongs to
  82073. */
  82074. function DeviceOrientationCamera(name, position, scene) {
  82075. var _this = _super.call(this, name, position, scene) || this;
  82076. _this._quaternionCache = new BABYLON.Quaternion();
  82077. _this.inputs.addDeviceOrientation();
  82078. return _this;
  82079. }
  82080. /**
  82081. * Gets the current instance class name ("DeviceOrientationCamera").
  82082. * This helps avoiding instanceof at run time.
  82083. * @returns the class name
  82084. */
  82085. DeviceOrientationCamera.prototype.getClassName = function () {
  82086. return "DeviceOrientationCamera";
  82087. };
  82088. /**
  82089. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  82090. */
  82091. DeviceOrientationCamera.prototype._checkInputs = function () {
  82092. _super.prototype._checkInputs.call(this);
  82093. this._quaternionCache.copyFrom(this.rotationQuaternion);
  82094. if (this._initialQuaternion) {
  82095. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  82096. }
  82097. };
  82098. /**
  82099. * Reset the camera to its default orientation on the specified axis only.
  82100. * @param axis The axis to reset
  82101. */
  82102. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  82103. var _this = this;
  82104. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  82105. //can only work if this camera has a rotation quaternion already.
  82106. if (!this.rotationQuaternion)
  82107. return;
  82108. if (!this._initialQuaternion) {
  82109. this._initialQuaternion = new BABYLON.Quaternion();
  82110. }
  82111. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  82112. ['x', 'y', 'z'].forEach(function (axisName) {
  82113. if (!axis[axisName]) {
  82114. _this._initialQuaternion[axisName] = 0;
  82115. }
  82116. else {
  82117. _this._initialQuaternion[axisName] *= -1;
  82118. }
  82119. });
  82120. this._initialQuaternion.normalize();
  82121. //force rotation update
  82122. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  82123. };
  82124. return DeviceOrientationCamera;
  82125. }(BABYLON.FreeCamera));
  82126. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  82127. })(BABYLON || (BABYLON = {}));
  82128. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  82129. "use strict";
  82130. var BABYLON;
  82131. (function (BABYLON) {
  82132. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  82133. __extends(VRDeviceOrientationFreeCamera, _super);
  82134. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  82135. if (compensateDistortion === void 0) { compensateDistortion = true; }
  82136. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  82137. var _this = _super.call(this, name, position, scene) || this;
  82138. vrCameraMetrics.compensateDistortion = compensateDistortion;
  82139. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  82140. return _this;
  82141. }
  82142. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  82143. return "VRDeviceOrientationFreeCamera";
  82144. };
  82145. return VRDeviceOrientationFreeCamera;
  82146. }(BABYLON.DeviceOrientationCamera));
  82147. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  82148. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  82149. __extends(VRDeviceOrientationGamepadCamera, _super);
  82150. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  82151. if (compensateDistortion === void 0) { compensateDistortion = true; }
  82152. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  82153. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  82154. _this.inputs.addGamepad();
  82155. return _this;
  82156. }
  82157. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  82158. return "VRDeviceOrientationGamepadCamera";
  82159. };
  82160. return VRDeviceOrientationGamepadCamera;
  82161. }(VRDeviceOrientationFreeCamera));
  82162. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  82163. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  82164. __extends(VRDeviceOrientationArcRotateCamera, _super);
  82165. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  82166. if (compensateDistortion === void 0) { compensateDistortion = true; }
  82167. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  82168. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  82169. vrCameraMetrics.compensateDistortion = compensateDistortion;
  82170. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  82171. _this.inputs.addVRDeviceOrientation();
  82172. return _this;
  82173. }
  82174. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  82175. return "VRDeviceOrientationArcRotateCamera";
  82176. };
  82177. return VRDeviceOrientationArcRotateCamera;
  82178. }(BABYLON.ArcRotateCamera));
  82179. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  82180. })(BABYLON || (BABYLON = {}));
  82181. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  82182. "use strict";
  82183. var BABYLON;
  82184. (function (BABYLON) {
  82185. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  82186. __extends(AnaglyphFreeCamera, _super);
  82187. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  82188. var _this = _super.call(this, name, position, scene) || this;
  82189. _this.interaxialDistance = interaxialDistance;
  82190. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  82191. return _this;
  82192. }
  82193. AnaglyphFreeCamera.prototype.getClassName = function () {
  82194. return "AnaglyphFreeCamera";
  82195. };
  82196. return AnaglyphFreeCamera;
  82197. }(BABYLON.FreeCamera));
  82198. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  82199. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  82200. __extends(AnaglyphArcRotateCamera, _super);
  82201. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  82202. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  82203. _this.interaxialDistance = interaxialDistance;
  82204. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  82205. return _this;
  82206. }
  82207. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  82208. return "AnaglyphArcRotateCamera";
  82209. };
  82210. return AnaglyphArcRotateCamera;
  82211. }(BABYLON.ArcRotateCamera));
  82212. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  82213. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  82214. __extends(AnaglyphGamepadCamera, _super);
  82215. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  82216. var _this = _super.call(this, name, position, scene) || this;
  82217. _this.interaxialDistance = interaxialDistance;
  82218. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  82219. return _this;
  82220. }
  82221. AnaglyphGamepadCamera.prototype.getClassName = function () {
  82222. return "AnaglyphGamepadCamera";
  82223. };
  82224. return AnaglyphGamepadCamera;
  82225. }(BABYLON.GamepadCamera));
  82226. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  82227. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  82228. __extends(AnaglyphUniversalCamera, _super);
  82229. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  82230. var _this = _super.call(this, name, position, scene) || this;
  82231. _this.interaxialDistance = interaxialDistance;
  82232. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  82233. return _this;
  82234. }
  82235. AnaglyphUniversalCamera.prototype.getClassName = function () {
  82236. return "AnaglyphUniversalCamera";
  82237. };
  82238. return AnaglyphUniversalCamera;
  82239. }(BABYLON.UniversalCamera));
  82240. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  82241. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  82242. __extends(StereoscopicFreeCamera, _super);
  82243. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  82244. var _this = _super.call(this, name, position, scene) || this;
  82245. _this.interaxialDistance = interaxialDistance;
  82246. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  82247. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  82248. return _this;
  82249. }
  82250. StereoscopicFreeCamera.prototype.getClassName = function () {
  82251. return "StereoscopicFreeCamera";
  82252. };
  82253. return StereoscopicFreeCamera;
  82254. }(BABYLON.FreeCamera));
  82255. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  82256. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  82257. __extends(StereoscopicArcRotateCamera, _super);
  82258. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  82259. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  82260. _this.interaxialDistance = interaxialDistance;
  82261. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  82262. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  82263. return _this;
  82264. }
  82265. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  82266. return "StereoscopicArcRotateCamera";
  82267. };
  82268. return StereoscopicArcRotateCamera;
  82269. }(BABYLON.ArcRotateCamera));
  82270. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  82271. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  82272. __extends(StereoscopicGamepadCamera, _super);
  82273. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  82274. var _this = _super.call(this, name, position, scene) || this;
  82275. _this.interaxialDistance = interaxialDistance;
  82276. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  82277. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  82278. return _this;
  82279. }
  82280. StereoscopicGamepadCamera.prototype.getClassName = function () {
  82281. return "StereoscopicGamepadCamera";
  82282. };
  82283. return StereoscopicGamepadCamera;
  82284. }(BABYLON.GamepadCamera));
  82285. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  82286. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  82287. __extends(StereoscopicUniversalCamera, _super);
  82288. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  82289. var _this = _super.call(this, name, position, scene) || this;
  82290. _this.interaxialDistance = interaxialDistance;
  82291. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  82292. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  82293. return _this;
  82294. }
  82295. StereoscopicUniversalCamera.prototype.getClassName = function () {
  82296. return "StereoscopicUniversalCamera";
  82297. };
  82298. return StereoscopicUniversalCamera;
  82299. }(BABYLON.UniversalCamera));
  82300. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  82301. })(BABYLON || (BABYLON = {}));
  82302. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  82303. "use strict";
  82304. var BABYLON;
  82305. (function (BABYLON) {
  82306. var VRExperienceHelperGazer = /** @class */ (function () {
  82307. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  82308. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  82309. this.scene = scene;
  82310. this._pointerDownOnMeshAsked = false;
  82311. this._isActionableMesh = false;
  82312. this._teleportationRequestInitiated = false;
  82313. this._teleportationBackRequestInitiated = false;
  82314. this._dpadPressed = true;
  82315. this._activePointer = false;
  82316. this._id = VRExperienceHelperGazer._idCounter++;
  82317. // Gaze tracker
  82318. if (!gazeTrackerToClone) {
  82319. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  82320. this._gazeTracker.bakeCurrentTransformIntoVertices();
  82321. this._gazeTracker.isPickable = false;
  82322. this._gazeTracker.isVisible = false;
  82323. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  82324. targetMat.specularColor = BABYLON.Color3.Black();
  82325. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  82326. targetMat.backFaceCulling = false;
  82327. this._gazeTracker.material = targetMat;
  82328. }
  82329. else {
  82330. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  82331. }
  82332. }
  82333. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  82334. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  82335. };
  82336. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  82337. this._pointerDownOnMeshAsked = true;
  82338. if (this._currentMeshSelected && this._currentHit) {
  82339. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  82340. }
  82341. };
  82342. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  82343. if (this._currentMeshSelected && this._currentHit) {
  82344. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  82345. }
  82346. this._pointerDownOnMeshAsked = false;
  82347. };
  82348. VRExperienceHelperGazer.prototype._activatePointer = function () {
  82349. this._activePointer = true;
  82350. };
  82351. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  82352. this._activePointer = false;
  82353. };
  82354. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  82355. };
  82356. VRExperienceHelperGazer.prototype.dispose = function () {
  82357. this._interactionsEnabled = false;
  82358. this._teleportationEnabled = false;
  82359. };
  82360. VRExperienceHelperGazer._idCounter = 0;
  82361. return VRExperienceHelperGazer;
  82362. }());
  82363. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  82364. __extends(VRExperienceHelperControllerGazer, _super);
  82365. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  82366. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  82367. _this.webVRController = webVRController;
  82368. // Laser pointer
  82369. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  82370. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  82371. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  82372. laserPointerMaterial.alpha = 0.6;
  82373. _this._laserPointer.material = laserPointerMaterial;
  82374. _this._laserPointer.rotation.x = Math.PI / 2;
  82375. _this._laserPointer.position.z = -0.5;
  82376. _this._laserPointer.isVisible = false;
  82377. if (!webVRController.mesh) {
  82378. // Create an empty mesh that is used prior to loading the high quality model
  82379. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  82380. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  82381. preloadPointerPose.rotation.x = -0.7;
  82382. preloadMesh.addChild(preloadPointerPose);
  82383. webVRController.attachToMesh(preloadMesh);
  82384. }
  82385. _this._setLaserPointerParent(webVRController.mesh);
  82386. return _this;
  82387. }
  82388. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  82389. return this.webVRController.getForwardRay(length);
  82390. };
  82391. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  82392. _super.prototype._activatePointer.call(this);
  82393. this._laserPointer.isVisible = true;
  82394. };
  82395. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  82396. _super.prototype._deactivatePointer.call(this);
  82397. this._laserPointer.isVisible = false;
  82398. };
  82399. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  82400. this._laserPointer.material.emissiveColor = color;
  82401. };
  82402. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  82403. var makeNotPick = function (root) {
  82404. root.name += " laserPointer";
  82405. root.getChildMeshes().forEach(function (c) {
  82406. makeNotPick(c);
  82407. });
  82408. };
  82409. makeNotPick(mesh);
  82410. var childMeshes = mesh.getChildMeshes();
  82411. this.webVRController._pointingPoseNode = null;
  82412. for (var i = 0; i < childMeshes.length; i++) {
  82413. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  82414. mesh = childMeshes[i];
  82415. this.webVRController._pointingPoseNode = mesh;
  82416. break;
  82417. }
  82418. }
  82419. this._laserPointer.parent = mesh;
  82420. };
  82421. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  82422. this._laserPointer.scaling.y = distance;
  82423. this._laserPointer.position.z = -distance / 2;
  82424. };
  82425. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  82426. _super.prototype.dispose.call(this);
  82427. this._laserPointer.dispose();
  82428. };
  82429. return VRExperienceHelperControllerGazer;
  82430. }(VRExperienceHelperGazer));
  82431. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  82432. __extends(VRExperienceHelperCameraGazer, _super);
  82433. function VRExperienceHelperCameraGazer(getCamera, scene) {
  82434. var _this = _super.call(this, scene) || this;
  82435. _this.getCamera = getCamera;
  82436. return _this;
  82437. }
  82438. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  82439. var camera = this.getCamera();
  82440. if (camera) {
  82441. return camera.getForwardRay(length);
  82442. }
  82443. else {
  82444. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  82445. }
  82446. };
  82447. return VRExperienceHelperCameraGazer;
  82448. }(VRExperienceHelperGazer));
  82449. /**
  82450. * Helps to quickly add VR support to an existing scene.
  82451. * See http://doc.babylonjs.com/how_to/webvr_helper
  82452. */
  82453. var VRExperienceHelper = /** @class */ (function () {
  82454. /**
  82455. * Instantiates a VRExperienceHelper.
  82456. * Helps to quickly add VR support to an existing scene.
  82457. * @param scene The scene the VRExperienceHelper belongs to.
  82458. * @param webVROptions Options to modify the vr experience helper's behavior.
  82459. */
  82460. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  82461. if (webVROptions === void 0) { webVROptions = {}; }
  82462. var _this = this;
  82463. this.webVROptions = webVROptions;
  82464. // Can the system support WebVR, even if a headset isn't plugged in?
  82465. this._webVRsupported = false;
  82466. // If WebVR is supported, is a headset plugged in and are we ready to present?
  82467. this._webVRready = false;
  82468. // Are we waiting for the requestPresent callback to complete?
  82469. this._webVRrequesting = false;
  82470. // Are we presenting to the headset right now?
  82471. this._webVRpresenting = false;
  82472. // Are we presenting in the fullscreen fallback?
  82473. this._fullscreenVRpresenting = false;
  82474. /**
  82475. * Observable raised when entering VR.
  82476. */
  82477. this.onEnteringVRObservable = new BABYLON.Observable();
  82478. /**
  82479. * Observable raised when exiting VR.
  82480. */
  82481. this.onExitingVRObservable = new BABYLON.Observable();
  82482. /**
  82483. * Observable raised when controller mesh is loaded.
  82484. */
  82485. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  82486. this._useCustomVRButton = false;
  82487. this._teleportationRequested = false;
  82488. this._teleportActive = false;
  82489. this._floorMeshesCollection = [];
  82490. this._rotationAllowed = true;
  82491. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  82492. this._rotationRightAsked = false;
  82493. this._rotationLeftAsked = false;
  82494. this._isDefaultTeleportationTarget = true;
  82495. this._teleportationFillColor = "#444444";
  82496. this._teleportationBorderColor = "#FFFFFF";
  82497. this._rotationAngle = 0;
  82498. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  82499. this._padSensibilityUp = 0.65;
  82500. this._padSensibilityDown = 0.35;
  82501. this.leftController = null;
  82502. this.rightController = null;
  82503. /**
  82504. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  82505. */
  82506. this.onNewMeshSelected = new BABYLON.Observable();
  82507. /**
  82508. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  82509. */
  82510. this.onNewMeshPicked = new BABYLON.Observable();
  82511. /**
  82512. * Observable raised before camera teleportation
  82513. */
  82514. this.onBeforeCameraTeleport = new BABYLON.Observable();
  82515. /**
  82516. * Observable raised after camera teleportation
  82517. */
  82518. this.onAfterCameraTeleport = new BABYLON.Observable();
  82519. /**
  82520. * Observable raised when current selected mesh gets unselected
  82521. */
  82522. this.onSelectedMeshUnselected = new BABYLON.Observable();
  82523. /**
  82524. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  82525. */
  82526. this.teleportationEnabled = true;
  82527. this._teleportationInitialized = false;
  82528. this._interactionsEnabled = false;
  82529. this._interactionsRequested = false;
  82530. this._displayGaze = true;
  82531. this._displayLaserPointer = true;
  82532. this._onResize = function () {
  82533. _this.moveButtonToBottomRight();
  82534. if (_this._fullscreenVRpresenting && _this._webVRready) {
  82535. _this.exitVR();
  82536. }
  82537. };
  82538. this._onFullscreenChange = function () {
  82539. if (document.fullscreen !== undefined) {
  82540. _this._fullscreenVRpresenting = document.fullscreen;
  82541. }
  82542. else if (document.mozFullScreen !== undefined) {
  82543. _this._fullscreenVRpresenting = document.mozFullScreen;
  82544. }
  82545. else if (document.webkitIsFullScreen !== undefined) {
  82546. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  82547. }
  82548. else if (document.msIsFullScreen !== undefined) {
  82549. _this._fullscreenVRpresenting = document.msIsFullScreen;
  82550. }
  82551. if (!_this._fullscreenVRpresenting && _this._canvas) {
  82552. _this.exitVR();
  82553. if (!_this._useCustomVRButton) {
  82554. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  82555. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  82556. }
  82557. }
  82558. };
  82559. this.beforeRender = function () {
  82560. if (_this.leftController && _this.leftController._activePointer) {
  82561. _this._castRayAndSelectObject(_this.leftController);
  82562. }
  82563. if (_this.rightController && _this.rightController._activePointer) {
  82564. _this._castRayAndSelectObject(_this.rightController);
  82565. }
  82566. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  82567. _this._castRayAndSelectObject(_this._cameraGazer);
  82568. }
  82569. else {
  82570. _this._cameraGazer._gazeTracker.isVisible = false;
  82571. }
  82572. };
  82573. this._onNewGamepadConnected = function (gamepad) {
  82574. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  82575. if (gamepad.leftStick) {
  82576. gamepad.onleftstickchanged(function (stickValues) {
  82577. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  82578. // Listening to classic/xbox gamepad only if no VR controller is active
  82579. if ((!_this.leftController && !_this.rightController) ||
  82580. ((_this.leftController && !_this.leftController._activePointer) &&
  82581. (_this.rightController && !_this.rightController._activePointer))) {
  82582. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  82583. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  82584. }
  82585. }
  82586. });
  82587. }
  82588. if (gamepad.rightStick) {
  82589. gamepad.onrightstickchanged(function (stickValues) {
  82590. if (_this._teleportationInitialized) {
  82591. _this._checkRotate(stickValues, _this._cameraGazer);
  82592. }
  82593. });
  82594. }
  82595. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  82596. gamepad.onbuttondown(function (buttonPressed) {
  82597. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  82598. _this._cameraGazer._selectionPointerDown();
  82599. }
  82600. });
  82601. gamepad.onbuttonup(function (buttonPressed) {
  82602. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  82603. _this._cameraGazer._selectionPointerUp();
  82604. }
  82605. });
  82606. }
  82607. }
  82608. else {
  82609. var webVRController = gamepad;
  82610. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  82611. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  82612. _this.rightController = controller;
  82613. }
  82614. else {
  82615. _this.leftController = controller;
  82616. }
  82617. _this._tryEnableInteractionOnController(controller);
  82618. }
  82619. };
  82620. // 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
  82621. this._tryEnableInteractionOnController = function (controller) {
  82622. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  82623. _this._enableInteractionOnController(controller);
  82624. }
  82625. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  82626. _this._enableTeleportationOnController(controller);
  82627. }
  82628. };
  82629. this._onNewGamepadDisconnected = function (gamepad) {
  82630. if (gamepad instanceof BABYLON.WebVRController) {
  82631. if (gamepad.hand === "left" && _this.leftController != null) {
  82632. _this.leftController.dispose();
  82633. _this.leftController = null;
  82634. }
  82635. if (gamepad.hand === "right" && _this.rightController != null) {
  82636. _this.rightController.dispose();
  82637. _this.rightController = null;
  82638. }
  82639. }
  82640. };
  82641. this._workingVector = BABYLON.Vector3.Zero();
  82642. this._workingQuaternion = BABYLON.Quaternion.Identity();
  82643. this._workingMatrix = BABYLON.Matrix.Identity();
  82644. this._scene = scene;
  82645. this._canvas = scene.getEngine().getRenderingCanvas();
  82646. // Parse options
  82647. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  82648. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  82649. }
  82650. if (webVROptions.createDeviceOrientationCamera === undefined) {
  82651. webVROptions.createDeviceOrientationCamera = true;
  82652. }
  82653. if (webVROptions.defaultHeight === undefined) {
  82654. webVROptions.defaultHeight = 1.7;
  82655. }
  82656. if (webVROptions.useCustomVRButton) {
  82657. this._useCustomVRButton = true;
  82658. if (webVROptions.customVRButton) {
  82659. this._btnVR = webVROptions.customVRButton;
  82660. }
  82661. }
  82662. if (webVROptions.rayLength) {
  82663. this._rayLength = webVROptions.rayLength;
  82664. }
  82665. this._defaultHeight = webVROptions.defaultHeight;
  82666. if (webVROptions.positionScale) {
  82667. this._rayLength *= webVROptions.positionScale;
  82668. this._defaultHeight *= webVROptions.positionScale;
  82669. }
  82670. // Set position
  82671. if (this._scene.activeCamera) {
  82672. this._position = this._scene.activeCamera.position.clone();
  82673. }
  82674. else {
  82675. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  82676. }
  82677. // Set non-vr camera
  82678. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  82679. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  82680. // Copy data from existing camera
  82681. if (this._scene.activeCamera) {
  82682. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  82683. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  82684. // Set rotation from previous camera
  82685. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  82686. var targetCamera = this._scene.activeCamera;
  82687. if (targetCamera.rotationQuaternion) {
  82688. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  82689. }
  82690. else {
  82691. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  82692. }
  82693. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  82694. }
  82695. }
  82696. this._scene.activeCamera = this._deviceOrientationCamera;
  82697. if (this._canvas) {
  82698. this._scene.activeCamera.attachControl(this._canvas);
  82699. }
  82700. }
  82701. else {
  82702. this._existingCamera = this._scene.activeCamera;
  82703. }
  82704. // Create VR cameras
  82705. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  82706. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  82707. }
  82708. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  82709. this._webVRCamera.useStandingMatrix();
  82710. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  82711. // Create default button
  82712. if (!this._useCustomVRButton) {
  82713. this._btnVR = document.createElement("BUTTON");
  82714. this._btnVR.className = "babylonVRicon";
  82715. this._btnVR.id = "babylonVRiconbtn";
  82716. this._btnVR.title = "Click to switch to VR";
  82717. 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) }";
  82718. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  82719. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  82720. // css += ".babylonVRicon.vrdisplaysupported { }";
  82721. // css += ".babylonVRicon.vrdisplayready { }";
  82722. // css += ".babylonVRicon.vrdisplayrequesting { }";
  82723. var style = document.createElement('style');
  82724. style.appendChild(document.createTextNode(css));
  82725. document.getElementsByTagName('head')[0].appendChild(style);
  82726. this.moveButtonToBottomRight();
  82727. }
  82728. // VR button click event
  82729. if (this._btnVR) {
  82730. this._btnVR.addEventListener("click", function () {
  82731. if (!_this.isInVRMode) {
  82732. _this.enterVR();
  82733. }
  82734. else {
  82735. _this.exitVR();
  82736. }
  82737. });
  82738. }
  82739. // Window events
  82740. window.addEventListener("resize", this._onResize);
  82741. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  82742. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  82743. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  82744. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  82745. // Display vr button when headset is connected
  82746. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  82747. this.displayVRButton();
  82748. }
  82749. else {
  82750. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  82751. if (e.vrDisplay) {
  82752. _this.displayVRButton();
  82753. }
  82754. });
  82755. }
  82756. // Exiting VR mode using 'ESC' key on desktop
  82757. this._onKeyDown = function (event) {
  82758. if (event.keyCode === 27 && _this.isInVRMode) {
  82759. _this.exitVR();
  82760. }
  82761. };
  82762. document.addEventListener("keydown", this._onKeyDown);
  82763. // Exiting VR mode double tapping the touch screen
  82764. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  82765. if (_this.isInVRMode) {
  82766. _this.exitVR();
  82767. if (_this._fullscreenVRpresenting) {
  82768. _this._scene.getEngine().switchFullscreen(true);
  82769. }
  82770. }
  82771. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  82772. // Listen for WebVR display changes
  82773. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  82774. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  82775. this._onVRRequestPresentStart = function () {
  82776. _this._webVRrequesting = true;
  82777. _this.updateButtonVisibility();
  82778. };
  82779. this._onVRRequestPresentComplete = function (success) {
  82780. _this._webVRrequesting = false;
  82781. _this.updateButtonVisibility();
  82782. };
  82783. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  82784. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  82785. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  82786. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  82787. scene.onDisposeObservable.add(function () {
  82788. _this.dispose();
  82789. });
  82790. // Gamepad connection events
  82791. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  82792. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  82793. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  82794. this.updateButtonVisibility();
  82795. //create easing functions
  82796. this._circleEase = new BABYLON.CircleEase();
  82797. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  82798. }
  82799. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  82800. /** Return this.onEnteringVRObservable
  82801. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  82802. */
  82803. get: function () {
  82804. return this.onEnteringVRObservable;
  82805. },
  82806. enumerable: true,
  82807. configurable: true
  82808. });
  82809. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  82810. /** Return this.onExitingVRObservable
  82811. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  82812. */
  82813. get: function () {
  82814. return this.onExitingVRObservable;
  82815. },
  82816. enumerable: true,
  82817. configurable: true
  82818. });
  82819. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  82820. /** Return this.onControllerMeshLoadedObservable
  82821. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  82822. */
  82823. get: function () {
  82824. return this.onControllerMeshLoadedObservable;
  82825. },
  82826. enumerable: true,
  82827. configurable: true
  82828. });
  82829. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  82830. /**
  82831. * The mesh used to display where the user is going to teleport.
  82832. */
  82833. get: function () {
  82834. return this._teleportationTarget;
  82835. },
  82836. /**
  82837. * Sets the mesh to be used to display where the user is going to teleport.
  82838. */
  82839. set: function (value) {
  82840. if (value) {
  82841. value.name = "teleportationTarget";
  82842. this._isDefaultTeleportationTarget = false;
  82843. this._teleportationTarget = value;
  82844. }
  82845. },
  82846. enumerable: true,
  82847. configurable: true
  82848. });
  82849. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  82850. /**
  82851. * The mesh used to display where the user is selecting,
  82852. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  82853. * See http://doc.babylonjs.com/resources/baking_transformations
  82854. */
  82855. get: function () {
  82856. return this._cameraGazer._gazeTracker;
  82857. },
  82858. set: function (value) {
  82859. if (value) {
  82860. this._cameraGazer._gazeTracker = value;
  82861. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  82862. this._cameraGazer._gazeTracker.isPickable = false;
  82863. this._cameraGazer._gazeTracker.isVisible = false;
  82864. this._cameraGazer._gazeTracker.name = "gazeTracker";
  82865. if (this.leftController) {
  82866. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  82867. }
  82868. if (this.rightController) {
  82869. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  82870. }
  82871. }
  82872. },
  82873. enumerable: true,
  82874. configurable: true
  82875. });
  82876. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  82877. /**
  82878. * If the ray of the gaze should be displayed.
  82879. */
  82880. get: function () {
  82881. return this._displayGaze;
  82882. },
  82883. /**
  82884. * Sets if the ray of the gaze should be displayed.
  82885. */
  82886. set: function (value) {
  82887. this._displayGaze = value;
  82888. if (!value) {
  82889. this._cameraGazer._gazeTracker.isVisible = false;
  82890. if (this.leftController) {
  82891. this.leftController._gazeTracker.isVisible = false;
  82892. }
  82893. if (this.rightController) {
  82894. this.rightController._gazeTracker.isVisible = false;
  82895. }
  82896. }
  82897. },
  82898. enumerable: true,
  82899. configurable: true
  82900. });
  82901. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  82902. /**
  82903. * If the ray of the LaserPointer should be displayed.
  82904. */
  82905. get: function () {
  82906. return this._displayLaserPointer;
  82907. },
  82908. /**
  82909. * Sets if the ray of the LaserPointer should be displayed.
  82910. */
  82911. set: function (value) {
  82912. this._displayLaserPointer = value;
  82913. if (!value) {
  82914. if (this.rightController) {
  82915. this.rightController._deactivatePointer();
  82916. this.rightController._gazeTracker.isVisible = false;
  82917. }
  82918. if (this.leftController) {
  82919. this.leftController._deactivatePointer();
  82920. this.leftController._gazeTracker.isVisible = false;
  82921. }
  82922. }
  82923. else {
  82924. if (this.rightController) {
  82925. this.rightController._activatePointer();
  82926. }
  82927. else if (this.leftController) {
  82928. this.leftController._activatePointer();
  82929. }
  82930. }
  82931. },
  82932. enumerable: true,
  82933. configurable: true
  82934. });
  82935. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  82936. /**
  82937. * The deviceOrientationCamera used as the camera when not in VR.
  82938. */
  82939. get: function () {
  82940. return this._deviceOrientationCamera;
  82941. },
  82942. enumerable: true,
  82943. configurable: true
  82944. });
  82945. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  82946. /**
  82947. * Based on the current WebVR support, returns the current VR camera used.
  82948. */
  82949. get: function () {
  82950. if (this._webVRready) {
  82951. return this._webVRCamera;
  82952. }
  82953. else {
  82954. return this._scene.activeCamera;
  82955. }
  82956. },
  82957. enumerable: true,
  82958. configurable: true
  82959. });
  82960. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  82961. /**
  82962. * The webVRCamera which is used when in VR.
  82963. */
  82964. get: function () {
  82965. return this._webVRCamera;
  82966. },
  82967. enumerable: true,
  82968. configurable: true
  82969. });
  82970. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  82971. /**
  82972. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  82973. */
  82974. get: function () {
  82975. return this._vrDeviceOrientationCamera;
  82976. },
  82977. enumerable: true,
  82978. configurable: true
  82979. });
  82980. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  82981. get: function () {
  82982. var result = this._cameraGazer._teleportationRequestInitiated
  82983. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  82984. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  82985. return result;
  82986. },
  82987. enumerable: true,
  82988. configurable: true
  82989. });
  82990. // Raised when one of the controller has loaded successfully its associated default mesh
  82991. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  82992. if (this.leftController && this.leftController.webVRController == webVRController) {
  82993. if (webVRController.mesh) {
  82994. this.leftController._setLaserPointerParent(webVRController.mesh);
  82995. }
  82996. }
  82997. if (this.rightController && this.rightController.webVRController == webVRController) {
  82998. if (webVRController.mesh) {
  82999. this.rightController._setLaserPointerParent(webVRController.mesh);
  83000. }
  83001. }
  83002. try {
  83003. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  83004. }
  83005. catch (err) {
  83006. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  83007. }
  83008. };
  83009. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  83010. /**
  83011. * Gets a value indicating if we are currently in VR mode.
  83012. */
  83013. get: function () {
  83014. return this._webVRpresenting || this._fullscreenVRpresenting;
  83015. },
  83016. enumerable: true,
  83017. configurable: true
  83018. });
  83019. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  83020. var vrDisplay = this._scene.getEngine().getVRDevice();
  83021. if (vrDisplay) {
  83022. var wasPresenting = this._webVRpresenting;
  83023. // A VR display is connected
  83024. this._webVRpresenting = vrDisplay.isPresenting;
  83025. if (wasPresenting && !this._webVRpresenting)
  83026. this.exitVR();
  83027. }
  83028. else {
  83029. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  83030. }
  83031. this.updateButtonVisibility();
  83032. };
  83033. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  83034. this._webVRsupported = eventArgs.vrSupported;
  83035. this._webVRready = !!eventArgs.vrDisplay;
  83036. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  83037. this.updateButtonVisibility();
  83038. };
  83039. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  83040. if (this._canvas && !this._useCustomVRButton) {
  83041. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  83042. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  83043. }
  83044. };
  83045. VRExperienceHelper.prototype.displayVRButton = function () {
  83046. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  83047. document.body.appendChild(this._btnVR);
  83048. this._btnVRDisplayed = true;
  83049. }
  83050. };
  83051. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  83052. if (!this._btnVR || this._useCustomVRButton) {
  83053. return;
  83054. }
  83055. this._btnVR.className = "babylonVRicon";
  83056. if (this.isInVRMode) {
  83057. this._btnVR.className += " vrdisplaypresenting";
  83058. }
  83059. else {
  83060. if (this._webVRready)
  83061. this._btnVR.className += " vrdisplayready";
  83062. if (this._webVRsupported)
  83063. this._btnVR.className += " vrdisplaysupported";
  83064. if (this._webVRrequesting)
  83065. this._btnVR.className += " vrdisplayrequesting";
  83066. }
  83067. };
  83068. /**
  83069. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  83070. * Otherwise, will use the fullscreen API.
  83071. */
  83072. VRExperienceHelper.prototype.enterVR = function () {
  83073. if (this.onEnteringVRObservable) {
  83074. try {
  83075. this.onEnteringVRObservable.notifyObservers(this);
  83076. }
  83077. catch (err) {
  83078. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  83079. }
  83080. }
  83081. if (this._scene.activeCamera) {
  83082. this._position = this._scene.activeCamera.position.clone();
  83083. // make sure that we return to the last active camera
  83084. this._existingCamera = this._scene.activeCamera;
  83085. }
  83086. if (this._webVRrequesting)
  83087. return;
  83088. // If WebVR is supported and a headset is connected
  83089. if (this._webVRready) {
  83090. if (!this._webVRpresenting) {
  83091. this._webVRCamera.position = this._position;
  83092. this._scene.activeCamera = this._webVRCamera;
  83093. }
  83094. }
  83095. else if (this._vrDeviceOrientationCamera) {
  83096. this._vrDeviceOrientationCamera.position = this._position;
  83097. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  83098. this._scene.getEngine().switchFullscreen(true);
  83099. this.updateButtonVisibility();
  83100. }
  83101. if (this._scene.activeCamera && this._canvas) {
  83102. this._scene.activeCamera.attachControl(this._canvas);
  83103. }
  83104. if (this._interactionsEnabled) {
  83105. this._scene.registerBeforeRender(this.beforeRender);
  83106. }
  83107. };
  83108. /**
  83109. * Attempt to exit VR, or fullscreen.
  83110. */
  83111. VRExperienceHelper.prototype.exitVR = function () {
  83112. if (this.onExitingVRObservable) {
  83113. try {
  83114. this.onExitingVRObservable.notifyObservers(this);
  83115. }
  83116. catch (err) {
  83117. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  83118. }
  83119. }
  83120. if (this._webVRpresenting) {
  83121. this._scene.getEngine().disableVR();
  83122. }
  83123. if (this._scene.activeCamera) {
  83124. this._position = this._scene.activeCamera.position.clone();
  83125. }
  83126. if (this._deviceOrientationCamera) {
  83127. this._deviceOrientationCamera.position = this._position;
  83128. this._scene.activeCamera = this._deviceOrientationCamera;
  83129. if (this._canvas) {
  83130. this._scene.activeCamera.attachControl(this._canvas);
  83131. }
  83132. }
  83133. else if (this._existingCamera) {
  83134. this._existingCamera.position = this._position;
  83135. this._scene.activeCamera = this._existingCamera;
  83136. }
  83137. this.updateButtonVisibility();
  83138. if (this._interactionsEnabled) {
  83139. this._scene.unregisterBeforeRender(this.beforeRender);
  83140. }
  83141. };
  83142. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  83143. /**
  83144. * The position of the vr experience helper.
  83145. */
  83146. get: function () {
  83147. return this._position;
  83148. },
  83149. /**
  83150. * Sets the position of the vr experience helper.
  83151. */
  83152. set: function (value) {
  83153. this._position = value;
  83154. if (this._scene.activeCamera) {
  83155. this._scene.activeCamera.position = value;
  83156. }
  83157. },
  83158. enumerable: true,
  83159. configurable: true
  83160. });
  83161. /**
  83162. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  83163. */
  83164. VRExperienceHelper.prototype.enableInteractions = function () {
  83165. var _this = this;
  83166. if (!this._interactionsEnabled) {
  83167. this._interactionsRequested = true;
  83168. if (this.leftController) {
  83169. this._enableInteractionOnController(this.leftController);
  83170. }
  83171. if (this.rightController) {
  83172. this._enableInteractionOnController(this.rightController);
  83173. }
  83174. this.raySelectionPredicate = function (mesh) {
  83175. return mesh.isVisible;
  83176. };
  83177. this.meshSelectionPredicate = function (mesh) {
  83178. return true;
  83179. };
  83180. this._raySelectionPredicate = function (mesh) {
  83181. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  83182. && mesh.name.indexOf("teleportationTarget") === -1
  83183. && mesh.name.indexOf("torusTeleportation") === -1
  83184. && mesh.name.indexOf("laserPointer") === -1)) {
  83185. return _this.raySelectionPredicate(mesh);
  83186. }
  83187. return false;
  83188. };
  83189. this._interactionsEnabled = true;
  83190. }
  83191. };
  83192. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  83193. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  83194. if (this._floorMeshesCollection[i].id === mesh.id) {
  83195. return true;
  83196. }
  83197. }
  83198. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  83199. return true;
  83200. }
  83201. return false;
  83202. };
  83203. /**
  83204. * Adds a floor mesh to be used for teleportation.
  83205. * @param floorMesh the mesh to be used for teleportation.
  83206. */
  83207. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  83208. if (!this._floorMeshesCollection) {
  83209. return;
  83210. }
  83211. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  83212. return;
  83213. }
  83214. this._floorMeshesCollection.push(floorMesh);
  83215. };
  83216. /**
  83217. * Removes a floor mesh from being used for teleportation.
  83218. * @param floorMesh the mesh to be removed.
  83219. */
  83220. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  83221. if (!this._floorMeshesCollection) {
  83222. return;
  83223. }
  83224. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  83225. if (meshIndex !== -1) {
  83226. this._floorMeshesCollection.splice(meshIndex, 1);
  83227. }
  83228. };
  83229. /**
  83230. * Enables interactions and teleportation using the VR controllers and gaze.
  83231. * @param vrTeleportationOptions options to modify teleportation behavior.
  83232. */
  83233. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  83234. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  83235. if (!this._teleportationInitialized) {
  83236. this._teleportationRequested = true;
  83237. this.enableInteractions();
  83238. if (vrTeleportationOptions.floorMeshName) {
  83239. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  83240. }
  83241. if (vrTeleportationOptions.floorMeshes) {
  83242. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  83243. }
  83244. if (this.leftController != null) {
  83245. this._enableTeleportationOnController(this.leftController);
  83246. }
  83247. if (this.rightController != null) {
  83248. this._enableTeleportationOnController(this.rightController);
  83249. }
  83250. // Creates an image processing post process for the vignette not relying
  83251. // on the main scene configuration for image processing to reduce setup and spaces
  83252. // (gamma/linear) conflicts.
  83253. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  83254. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  83255. imageProcessingConfiguration.vignetteEnabled = true;
  83256. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  83257. this._webVRCamera.detachPostProcess(this._postProcessMove);
  83258. this._teleportationInitialized = true;
  83259. if (this._isDefaultTeleportationTarget) {
  83260. this._createTeleportationCircles();
  83261. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  83262. }
  83263. }
  83264. };
  83265. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  83266. var _this = this;
  83267. var controllerMesh = controller.webVRController.mesh;
  83268. if (controllerMesh) {
  83269. controller._interactionsEnabled = true;
  83270. controller._activatePointer();
  83271. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  83272. // Enabling / disabling laserPointer
  83273. if (_this._displayLaserPointer && stateObject.value === 1) {
  83274. if (controller._activePointer) {
  83275. controller._deactivatePointer();
  83276. }
  83277. else {
  83278. controller._activatePointer();
  83279. }
  83280. if (_this.displayGaze) {
  83281. controller._gazeTracker.isVisible = controller._activePointer;
  83282. }
  83283. }
  83284. });
  83285. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  83286. if (!controller._pointerDownOnMeshAsked) {
  83287. if (stateObject.value > _this._padSensibilityUp) {
  83288. controller._selectionPointerDown();
  83289. }
  83290. }
  83291. else if (stateObject.value < _this._padSensibilityDown) {
  83292. controller._selectionPointerUp();
  83293. }
  83294. });
  83295. }
  83296. };
  83297. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  83298. // Dont teleport if another gaze already requested teleportation
  83299. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  83300. return;
  83301. }
  83302. if (!gazer._teleportationRequestInitiated) {
  83303. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  83304. gazer._activatePointer();
  83305. gazer._teleportationRequestInitiated = true;
  83306. }
  83307. }
  83308. else {
  83309. // Listening to the proper controller values changes to confirm teleportation
  83310. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  83311. if (this._teleportActive) {
  83312. this._teleportCamera(this._haloCenter);
  83313. }
  83314. gazer._teleportationRequestInitiated = false;
  83315. }
  83316. }
  83317. };
  83318. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  83319. // Only rotate when user is not currently selecting a teleportation location
  83320. if (gazer._teleportationRequestInitiated) {
  83321. return;
  83322. }
  83323. if (!this._rotationLeftAsked) {
  83324. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  83325. this._rotationLeftAsked = true;
  83326. if (this._rotationAllowed) {
  83327. this._rotateCamera(false);
  83328. }
  83329. }
  83330. }
  83331. else {
  83332. if (stateObject.x > -this._padSensibilityDown) {
  83333. this._rotationLeftAsked = false;
  83334. }
  83335. }
  83336. if (!this._rotationRightAsked) {
  83337. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  83338. this._rotationRightAsked = true;
  83339. if (this._rotationAllowed) {
  83340. this._rotateCamera(true);
  83341. }
  83342. }
  83343. }
  83344. else {
  83345. if (stateObject.x < this._padSensibilityDown) {
  83346. this._rotationRightAsked = false;
  83347. }
  83348. }
  83349. };
  83350. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  83351. // Only teleport backwards when user is not currently selecting a teleportation location
  83352. if (gazer._teleportationRequestInitiated) {
  83353. return;
  83354. }
  83355. // Teleport backwards
  83356. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  83357. if (!gazer._teleportationBackRequestInitiated) {
  83358. if (!this.currentVRCamera) {
  83359. return;
  83360. }
  83361. // Get rotation and position of the current camera
  83362. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  83363. var position = this.currentVRCamera.position;
  83364. // If the camera has device position, use that instead
  83365. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  83366. rotation = this.currentVRCamera.deviceRotationQuaternion;
  83367. position = this.currentVRCamera.devicePosition;
  83368. }
  83369. // Get matrix with only the y rotation of the device rotation
  83370. rotation.toEulerAnglesToRef(this._workingVector);
  83371. this._workingVector.z = 0;
  83372. this._workingVector.x = 0;
  83373. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  83374. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  83375. // Rotate backwards ray by device rotation to cast at the ground behind the user
  83376. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  83377. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  83378. var ray = new BABYLON.Ray(position, this._workingVector);
  83379. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  83380. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  83381. this._teleportCamera(hit.pickedPoint);
  83382. }
  83383. gazer._teleportationBackRequestInitiated = true;
  83384. }
  83385. }
  83386. else {
  83387. gazer._teleportationBackRequestInitiated = false;
  83388. }
  83389. };
  83390. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  83391. var _this = this;
  83392. var controllerMesh = controller.webVRController.mesh;
  83393. if (controllerMesh) {
  83394. if (!controller._interactionsEnabled) {
  83395. this._enableInteractionOnController(controller);
  83396. }
  83397. controller._interactionsEnabled = true;
  83398. controller._teleportationEnabled = true;
  83399. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  83400. controller._dpadPressed = false;
  83401. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  83402. controller._dpadPressed = stateObject.pressed;
  83403. if (!controller._dpadPressed) {
  83404. _this._rotationLeftAsked = false;
  83405. _this._rotationRightAsked = false;
  83406. controller._teleportationBackRequestInitiated = false;
  83407. }
  83408. });
  83409. }
  83410. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  83411. if (_this.teleportationEnabled) {
  83412. _this._checkTeleportBackwards(stateObject, controller);
  83413. _this._checkTeleportWithRay(stateObject, controller);
  83414. }
  83415. _this._checkRotate(stateObject, controller);
  83416. });
  83417. }
  83418. };
  83419. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  83420. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  83421. this._teleportationTarget.isPickable = false;
  83422. var length = 512;
  83423. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  83424. dynamicTexture.hasAlpha = true;
  83425. var context = dynamicTexture.getContext();
  83426. var centerX = length / 2;
  83427. var centerY = length / 2;
  83428. var radius = 200;
  83429. context.beginPath();
  83430. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  83431. context.fillStyle = this._teleportationFillColor;
  83432. context.fill();
  83433. context.lineWidth = 10;
  83434. context.strokeStyle = this._teleportationBorderColor;
  83435. context.stroke();
  83436. context.closePath();
  83437. dynamicTexture.update();
  83438. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  83439. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  83440. this._teleportationTarget.material = teleportationCircleMaterial;
  83441. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  83442. torus.isPickable = false;
  83443. torus.parent = this._teleportationTarget;
  83444. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  83445. var keys = [];
  83446. keys.push({
  83447. frame: 0,
  83448. value: 0
  83449. });
  83450. keys.push({
  83451. frame: 30,
  83452. value: 0.4
  83453. });
  83454. keys.push({
  83455. frame: 60,
  83456. value: 0
  83457. });
  83458. animationInnerCircle.setKeys(keys);
  83459. var easingFunction = new BABYLON.SineEase();
  83460. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  83461. animationInnerCircle.setEasingFunction(easingFunction);
  83462. torus.animations = [];
  83463. torus.animations.push(animationInnerCircle);
  83464. this._scene.beginAnimation(torus, 0, 60, true);
  83465. this._hideTeleportationTarget();
  83466. };
  83467. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  83468. this._teleportActive = true;
  83469. if (this._teleportationInitialized) {
  83470. this._teleportationTarget.isVisible = true;
  83471. if (this._isDefaultTeleportationTarget) {
  83472. this._teleportationTarget.getChildren()[0].isVisible = true;
  83473. }
  83474. }
  83475. };
  83476. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  83477. this._teleportActive = false;
  83478. if (this._teleportationInitialized) {
  83479. this._teleportationTarget.isVisible = false;
  83480. if (this._isDefaultTeleportationTarget) {
  83481. this._teleportationTarget.getChildren()[0].isVisible = false;
  83482. }
  83483. }
  83484. };
  83485. VRExperienceHelper.prototype._rotateCamera = function (right) {
  83486. var _this = this;
  83487. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  83488. return;
  83489. }
  83490. if (right) {
  83491. this._rotationAngle++;
  83492. }
  83493. else {
  83494. this._rotationAngle--;
  83495. }
  83496. this.currentVRCamera.animations = [];
  83497. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  83498. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83499. var animationRotationKeys = [];
  83500. animationRotationKeys.push({
  83501. frame: 0,
  83502. value: this.currentVRCamera.rotationQuaternion
  83503. });
  83504. animationRotationKeys.push({
  83505. frame: 6,
  83506. value: target
  83507. });
  83508. animationRotation.setKeys(animationRotationKeys);
  83509. animationRotation.setEasingFunction(this._circleEase);
  83510. this.currentVRCamera.animations.push(animationRotation);
  83511. this._postProcessMove.animations = [];
  83512. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83513. var vignetteWeightKeys = [];
  83514. vignetteWeightKeys.push({
  83515. frame: 0,
  83516. value: 0
  83517. });
  83518. vignetteWeightKeys.push({
  83519. frame: 3,
  83520. value: 4
  83521. });
  83522. vignetteWeightKeys.push({
  83523. frame: 6,
  83524. value: 0
  83525. });
  83526. animationPP.setKeys(vignetteWeightKeys);
  83527. animationPP.setEasingFunction(this._circleEase);
  83528. this._postProcessMove.animations.push(animationPP);
  83529. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83530. var vignetteStretchKeys = [];
  83531. vignetteStretchKeys.push({
  83532. frame: 0,
  83533. value: 0
  83534. });
  83535. vignetteStretchKeys.push({
  83536. frame: 3,
  83537. value: 10
  83538. });
  83539. vignetteStretchKeys.push({
  83540. frame: 6,
  83541. value: 0
  83542. });
  83543. animationPP2.setKeys(vignetteStretchKeys);
  83544. animationPP2.setEasingFunction(this._circleEase);
  83545. this._postProcessMove.animations.push(animationPP2);
  83546. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  83547. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  83548. this._postProcessMove.samples = 4;
  83549. this._webVRCamera.attachPostProcess(this._postProcessMove);
  83550. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  83551. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  83552. });
  83553. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  83554. };
  83555. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer) {
  83556. if (hit.pickedPoint) {
  83557. if (gazer._teleportationRequestInitiated) {
  83558. this._displayTeleportationTarget();
  83559. this._haloCenter.copyFrom(hit.pickedPoint);
  83560. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  83561. }
  83562. var pickNormal = hit.getNormal(true, false);
  83563. if (pickNormal) {
  83564. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  83565. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  83566. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  83567. }
  83568. this._teleportationTarget.position.y += 0.1;
  83569. }
  83570. };
  83571. VRExperienceHelper.prototype._teleportCamera = function (location) {
  83572. var _this = this;
  83573. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  83574. return;
  83575. }
  83576. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  83577. // offset of the headset from the anchor.
  83578. if (this.webVRCamera.leftCamera) {
  83579. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  83580. this._workingVector.subtractInPlace(this.webVRCamera.position);
  83581. location.subtractToRef(this._workingVector, this._workingVector);
  83582. }
  83583. else {
  83584. this._workingVector.copyFrom(location);
  83585. }
  83586. // Add height to account for user's height offset
  83587. if (this.isInVRMode) {
  83588. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  83589. }
  83590. else {
  83591. this._workingVector.y += this._defaultHeight;
  83592. }
  83593. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  83594. // Create animation from the camera's position to the new location
  83595. this.currentVRCamera.animations = [];
  83596. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83597. var animationCameraTeleportationKeys = [{
  83598. frame: 0,
  83599. value: this.currentVRCamera.position
  83600. },
  83601. {
  83602. frame: 11,
  83603. value: this._workingVector
  83604. }
  83605. ];
  83606. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  83607. animationCameraTeleportation.setEasingFunction(this._circleEase);
  83608. this.currentVRCamera.animations.push(animationCameraTeleportation);
  83609. this._postProcessMove.animations = [];
  83610. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83611. var vignetteWeightKeys = [];
  83612. vignetteWeightKeys.push({
  83613. frame: 0,
  83614. value: 0
  83615. });
  83616. vignetteWeightKeys.push({
  83617. frame: 5,
  83618. value: 8
  83619. });
  83620. vignetteWeightKeys.push({
  83621. frame: 11,
  83622. value: 0
  83623. });
  83624. animationPP.setKeys(vignetteWeightKeys);
  83625. this._postProcessMove.animations.push(animationPP);
  83626. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  83627. var vignetteStretchKeys = [];
  83628. vignetteStretchKeys.push({
  83629. frame: 0,
  83630. value: 0
  83631. });
  83632. vignetteStretchKeys.push({
  83633. frame: 5,
  83634. value: 10
  83635. });
  83636. vignetteStretchKeys.push({
  83637. frame: 11,
  83638. value: 0
  83639. });
  83640. animationPP2.setKeys(vignetteStretchKeys);
  83641. this._postProcessMove.animations.push(animationPP2);
  83642. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  83643. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  83644. this._webVRCamera.attachPostProcess(this._postProcessMove);
  83645. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  83646. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  83647. });
  83648. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  83649. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  83650. });
  83651. this._hideTeleportationTarget();
  83652. };
  83653. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  83654. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  83655. return;
  83656. }
  83657. var hit = this._scene.pickWithRay(gazer._getForwardRay(this._rayLength), this._raySelectionPredicate);
  83658. // Moving the gazeTracker on the mesh face targetted
  83659. if (hit && hit.pickedPoint) {
  83660. if (this._displayGaze) {
  83661. var multiplier = 1;
  83662. gazer._gazeTracker.isVisible = true;
  83663. if (gazer._isActionableMesh) {
  83664. multiplier = 3;
  83665. }
  83666. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  83667. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  83668. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  83669. var pickNormal = hit.getNormal();
  83670. // To avoid z-fighting
  83671. var deltaFighting = 0.002;
  83672. if (pickNormal) {
  83673. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  83674. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  83675. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  83676. }
  83677. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  83678. if (gazer._gazeTracker.position.x < 0) {
  83679. gazer._gazeTracker.position.x += deltaFighting;
  83680. }
  83681. else {
  83682. gazer._gazeTracker.position.x -= deltaFighting;
  83683. }
  83684. if (gazer._gazeTracker.position.y < 0) {
  83685. gazer._gazeTracker.position.y += deltaFighting;
  83686. }
  83687. else {
  83688. gazer._gazeTracker.position.y -= deltaFighting;
  83689. }
  83690. if (gazer._gazeTracker.position.z < 0) {
  83691. gazer._gazeTracker.position.z += deltaFighting;
  83692. }
  83693. else {
  83694. gazer._gazeTracker.position.z -= deltaFighting;
  83695. }
  83696. }
  83697. // Changing the size of the laser pointer based on the distance from the targetted point
  83698. gazer._updatePointerDistance(hit.distance);
  83699. }
  83700. else {
  83701. gazer._gazeTracker.isVisible = false;
  83702. }
  83703. if (hit && hit.pickedMesh) {
  83704. gazer._currentHit = hit;
  83705. if (gazer._pointerDownOnMeshAsked) {
  83706. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  83707. }
  83708. // The object selected is the floor, we're in a teleportation scenario
  83709. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  83710. // Moving the teleportation area to this targetted point
  83711. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  83712. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  83713. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  83714. }
  83715. gazer._currentMeshSelected = null;
  83716. if (gazer._teleportationRequestInitiated) {
  83717. this._moveTeleportationSelectorTo(hit, gazer);
  83718. }
  83719. return;
  83720. }
  83721. // If not, we're in a selection scenario
  83722. //this._teleportationAllowed = false;
  83723. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  83724. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  83725. this.onNewMeshPicked.notifyObservers(hit);
  83726. gazer._currentMeshSelected = hit.pickedMesh;
  83727. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  83728. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  83729. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  83730. gazer._isActionableMesh = true;
  83731. }
  83732. else {
  83733. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83734. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83735. gazer._isActionableMesh = false;
  83736. }
  83737. try {
  83738. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  83739. }
  83740. catch (err) {
  83741. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  83742. }
  83743. }
  83744. else {
  83745. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  83746. gazer._currentMeshSelected = null;
  83747. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83748. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83749. }
  83750. }
  83751. }
  83752. else {
  83753. gazer._currentHit = null;
  83754. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  83755. gazer._currentMeshSelected = null;
  83756. //this._teleportationAllowed = false;
  83757. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83758. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  83759. }
  83760. };
  83761. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  83762. if (mesh) {
  83763. this.onSelectedMeshUnselected.notifyObservers(mesh);
  83764. }
  83765. };
  83766. /**
  83767. * Sets the color of the laser ray from the vr controllers.
  83768. * @param color new color for the ray.
  83769. */
  83770. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  83771. if (this.leftController) {
  83772. this.leftController._setLaserPointerColor(color);
  83773. }
  83774. if (this.rightController) {
  83775. this.rightController._setLaserPointerColor(color);
  83776. }
  83777. };
  83778. /**
  83779. * Sets the color of the ray from the vr headsets gaze.
  83780. * @param color new color for the ray.
  83781. */
  83782. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  83783. if (!this._cameraGazer._gazeTracker.material) {
  83784. return;
  83785. }
  83786. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  83787. if (this.leftController) {
  83788. this.leftController._gazeTracker.material.emissiveColor = color;
  83789. }
  83790. if (this.rightController) {
  83791. this.rightController._gazeTracker.material.emissiveColor = color;
  83792. }
  83793. };
  83794. /**
  83795. * Exits VR and disposes of the vr experience helper
  83796. */
  83797. VRExperienceHelper.prototype.dispose = function () {
  83798. if (this.isInVRMode) {
  83799. this.exitVR();
  83800. }
  83801. if (this._postProcessMove) {
  83802. this._postProcessMove.dispose();
  83803. }
  83804. if (this._webVRCamera) {
  83805. this._webVRCamera.dispose();
  83806. }
  83807. if (this._vrDeviceOrientationCamera) {
  83808. this._vrDeviceOrientationCamera.dispose();
  83809. }
  83810. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  83811. document.body.removeChild(this._btnVR);
  83812. }
  83813. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  83814. this._deviceOrientationCamera.dispose();
  83815. }
  83816. if (this._cameraGazer) {
  83817. this._cameraGazer.dispose();
  83818. }
  83819. if (this.leftController) {
  83820. this.leftController.dispose();
  83821. }
  83822. if (this.rightController) {
  83823. this.rightController.dispose();
  83824. }
  83825. if (this._teleportationTarget) {
  83826. this._teleportationTarget.dispose();
  83827. }
  83828. this._floorMeshesCollection = [];
  83829. document.removeEventListener("keydown", this._onKeyDown);
  83830. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  83831. window.removeEventListener("resize", this._onResize);
  83832. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  83833. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  83834. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  83835. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  83836. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  83837. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  83838. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  83839. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  83840. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  83841. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  83842. this._scene.unregisterBeforeRender(this.beforeRender);
  83843. };
  83844. /**
  83845. * Gets the name of the VRExperienceHelper class
  83846. * @returns "VRExperienceHelper"
  83847. */
  83848. VRExperienceHelper.prototype.getClassName = function () {
  83849. return "VRExperienceHelper";
  83850. };
  83851. return VRExperienceHelper;
  83852. }());
  83853. BABYLON.VRExperienceHelper = VRExperienceHelper;
  83854. })(BABYLON || (BABYLON = {}));
  83855. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  83856. "use strict";
  83857. // Mainly based on these 2 articles :
  83858. // 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
  83859. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  83860. var BABYLON;
  83861. (function (BABYLON) {
  83862. var JoystickAxis;
  83863. (function (JoystickAxis) {
  83864. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  83865. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  83866. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  83867. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  83868. var VirtualJoystick = /** @class */ (function () {
  83869. function VirtualJoystick(leftJoystick) {
  83870. var _this = this;
  83871. if (leftJoystick) {
  83872. this._leftJoystick = true;
  83873. }
  83874. else {
  83875. this._leftJoystick = false;
  83876. }
  83877. VirtualJoystick._globalJoystickIndex++;
  83878. // By default left & right arrow keys are moving the X
  83879. // and up & down keys are moving the Y
  83880. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  83881. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  83882. this.reverseLeftRight = false;
  83883. this.reverseUpDown = false;
  83884. // collections of pointers
  83885. this._touches = new BABYLON.StringDictionary();
  83886. this.deltaPosition = BABYLON.Vector3.Zero();
  83887. this._joystickSensibility = 25;
  83888. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  83889. this._onResize = function (evt) {
  83890. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  83891. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  83892. if (VirtualJoystick.vjCanvas) {
  83893. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  83894. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  83895. }
  83896. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  83897. };
  83898. // injecting a canvas element on top of the canvas 3D game
  83899. if (!VirtualJoystick.vjCanvas) {
  83900. window.addEventListener("resize", this._onResize, false);
  83901. VirtualJoystick.vjCanvas = document.createElement("canvas");
  83902. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  83903. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  83904. VirtualJoystick.vjCanvas.width = window.innerWidth;
  83905. VirtualJoystick.vjCanvas.height = window.innerHeight;
  83906. VirtualJoystick.vjCanvas.style.width = "100%";
  83907. VirtualJoystick.vjCanvas.style.height = "100%";
  83908. VirtualJoystick.vjCanvas.style.position = "absolute";
  83909. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  83910. VirtualJoystick.vjCanvas.style.top = "0px";
  83911. VirtualJoystick.vjCanvas.style.left = "0px";
  83912. VirtualJoystick.vjCanvas.style.zIndex = "5";
  83913. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  83914. // Support for jQuery PEP polyfill
  83915. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  83916. var context = VirtualJoystick.vjCanvas.getContext('2d');
  83917. if (!context) {
  83918. throw new Error("Unable to create canvas for virtual joystick");
  83919. }
  83920. VirtualJoystick.vjCanvasContext = context;
  83921. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  83922. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  83923. document.body.appendChild(VirtualJoystick.vjCanvas);
  83924. }
  83925. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  83926. this.pressed = false;
  83927. // default joystick color
  83928. this._joystickColor = "cyan";
  83929. this._joystickPointerID = -1;
  83930. // current joystick position
  83931. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  83932. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  83933. // origin joystick position
  83934. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  83935. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  83936. this._onPointerDownHandlerRef = function (evt) {
  83937. _this._onPointerDown(evt);
  83938. };
  83939. this._onPointerMoveHandlerRef = function (evt) {
  83940. _this._onPointerMove(evt);
  83941. };
  83942. this._onPointerUpHandlerRef = function (evt) {
  83943. _this._onPointerUp(evt);
  83944. };
  83945. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  83946. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  83947. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  83948. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  83949. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  83950. evt.preventDefault(); // Disables system menu
  83951. }, false);
  83952. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  83953. }
  83954. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  83955. this._joystickSensibility = newJoystickSensibility;
  83956. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  83957. };
  83958. VirtualJoystick.prototype._onPointerDown = function (e) {
  83959. var positionOnScreenCondition;
  83960. e.preventDefault();
  83961. if (this._leftJoystick === true) {
  83962. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  83963. }
  83964. else {
  83965. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  83966. }
  83967. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  83968. // First contact will be dedicated to the virtual joystick
  83969. this._joystickPointerID = e.pointerId;
  83970. this._joystickPointerStartPos.x = e.clientX;
  83971. this._joystickPointerStartPos.y = e.clientY;
  83972. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  83973. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  83974. this._deltaJoystickVector.x = 0;
  83975. this._deltaJoystickVector.y = 0;
  83976. this.pressed = true;
  83977. this._touches.add(e.pointerId.toString(), e);
  83978. }
  83979. else {
  83980. // You can only trigger the action buttons with a joystick declared
  83981. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  83982. this._action();
  83983. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  83984. }
  83985. }
  83986. };
  83987. VirtualJoystick.prototype._onPointerMove = function (e) {
  83988. // If the current pointer is the one associated to the joystick (first touch contact)
  83989. if (this._joystickPointerID == e.pointerId) {
  83990. this._joystickPointerPos.x = e.clientX;
  83991. this._joystickPointerPos.y = e.clientY;
  83992. this._deltaJoystickVector = this._joystickPointerPos.clone();
  83993. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  83994. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  83995. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  83996. switch (this._axisTargetedByLeftAndRight) {
  83997. case JoystickAxis.X:
  83998. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  83999. break;
  84000. case JoystickAxis.Y:
  84001. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  84002. break;
  84003. case JoystickAxis.Z:
  84004. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  84005. break;
  84006. }
  84007. var directionUpDown = this.reverseUpDown ? 1 : -1;
  84008. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  84009. switch (this._axisTargetedByUpAndDown) {
  84010. case JoystickAxis.X:
  84011. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  84012. break;
  84013. case JoystickAxis.Y:
  84014. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  84015. break;
  84016. case JoystickAxis.Z:
  84017. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  84018. break;
  84019. }
  84020. }
  84021. else {
  84022. var data = this._touches.get(e.pointerId.toString());
  84023. if (data) {
  84024. data.x = e.clientX;
  84025. data.y = e.clientY;
  84026. }
  84027. }
  84028. };
  84029. VirtualJoystick.prototype._onPointerUp = function (e) {
  84030. if (this._joystickPointerID == e.pointerId) {
  84031. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  84032. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  84033. this._joystickPointerID = -1;
  84034. this.pressed = false;
  84035. }
  84036. else {
  84037. var touch = this._touches.get(e.pointerId.toString());
  84038. if (touch) {
  84039. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  84040. }
  84041. }
  84042. this._deltaJoystickVector.x = 0;
  84043. this._deltaJoystickVector.y = 0;
  84044. this._touches.remove(e.pointerId.toString());
  84045. };
  84046. /**
  84047. * Change the color of the virtual joystick
  84048. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  84049. */
  84050. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  84051. this._joystickColor = newColor;
  84052. };
  84053. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  84054. this._action = action;
  84055. };
  84056. // Define which axis you'd like to control for left & right
  84057. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  84058. switch (axis) {
  84059. case JoystickAxis.X:
  84060. case JoystickAxis.Y:
  84061. case JoystickAxis.Z:
  84062. this._axisTargetedByLeftAndRight = axis;
  84063. break;
  84064. default:
  84065. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  84066. break;
  84067. }
  84068. };
  84069. // Define which axis you'd like to control for up & down
  84070. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  84071. switch (axis) {
  84072. case JoystickAxis.X:
  84073. case JoystickAxis.Y:
  84074. case JoystickAxis.Z:
  84075. this._axisTargetedByUpAndDown = axis;
  84076. break;
  84077. default:
  84078. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  84079. break;
  84080. }
  84081. };
  84082. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  84083. var _this = this;
  84084. if (this.pressed) {
  84085. this._touches.forEach(function (key, touch) {
  84086. if (touch.pointerId === _this._joystickPointerID) {
  84087. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  84088. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  84089. VirtualJoystick.vjCanvasContext.beginPath();
  84090. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  84091. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  84092. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  84093. VirtualJoystick.vjCanvasContext.stroke();
  84094. VirtualJoystick.vjCanvasContext.closePath();
  84095. VirtualJoystick.vjCanvasContext.beginPath();
  84096. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  84097. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  84098. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  84099. VirtualJoystick.vjCanvasContext.stroke();
  84100. VirtualJoystick.vjCanvasContext.closePath();
  84101. VirtualJoystick.vjCanvasContext.beginPath();
  84102. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  84103. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  84104. VirtualJoystick.vjCanvasContext.stroke();
  84105. VirtualJoystick.vjCanvasContext.closePath();
  84106. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  84107. }
  84108. else {
  84109. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  84110. VirtualJoystick.vjCanvasContext.beginPath();
  84111. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  84112. VirtualJoystick.vjCanvasContext.beginPath();
  84113. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  84114. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  84115. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  84116. VirtualJoystick.vjCanvasContext.stroke();
  84117. VirtualJoystick.vjCanvasContext.closePath();
  84118. touch.prevX = touch.x;
  84119. touch.prevY = touch.y;
  84120. }
  84121. ;
  84122. });
  84123. }
  84124. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  84125. };
  84126. VirtualJoystick.prototype.releaseCanvas = function () {
  84127. if (VirtualJoystick.vjCanvas) {
  84128. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  84129. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  84130. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  84131. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  84132. window.removeEventListener("resize", this._onResize);
  84133. document.body.removeChild(VirtualJoystick.vjCanvas);
  84134. VirtualJoystick.vjCanvas = null;
  84135. }
  84136. };
  84137. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  84138. VirtualJoystick._globalJoystickIndex = 0;
  84139. return VirtualJoystick;
  84140. }());
  84141. BABYLON.VirtualJoystick = VirtualJoystick;
  84142. })(BABYLON || (BABYLON = {}));
  84143. //# sourceMappingURL=babylon.virtualJoystick.js.map
  84144. "use strict";
  84145. var BABYLON;
  84146. (function (BABYLON) {
  84147. // We're mainly based on the logic defined into the FreeCamera code
  84148. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  84149. __extends(VirtualJoysticksCamera, _super);
  84150. function VirtualJoysticksCamera(name, position, scene) {
  84151. var _this = _super.call(this, name, position, scene) || this;
  84152. _this.inputs.addVirtualJoystick();
  84153. return _this;
  84154. }
  84155. VirtualJoysticksCamera.prototype.getClassName = function () {
  84156. return "VirtualJoysticksCamera";
  84157. };
  84158. return VirtualJoysticksCamera;
  84159. }(BABYLON.FreeCamera));
  84160. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  84161. })(BABYLON || (BABYLON = {}));
  84162. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  84163. "use strict";
  84164. var BABYLON;
  84165. (function (BABYLON) {
  84166. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  84167. function FreeCameraVirtualJoystickInput() {
  84168. }
  84169. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  84170. return this._leftjoystick;
  84171. };
  84172. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  84173. return this._rightjoystick;
  84174. };
  84175. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  84176. if (this._leftjoystick) {
  84177. var camera = this.camera;
  84178. var speed = camera._computeLocalCameraSpeed() * 50;
  84179. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  84180. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  84181. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  84182. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  84183. if (!this._leftjoystick.pressed) {
  84184. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  84185. }
  84186. if (!this._rightjoystick.pressed) {
  84187. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  84188. }
  84189. }
  84190. };
  84191. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  84192. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  84193. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  84194. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  84195. this._leftjoystick.setJoystickSensibility(0.15);
  84196. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  84197. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  84198. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  84199. this._rightjoystick.reverseUpDown = true;
  84200. this._rightjoystick.setJoystickSensibility(0.05);
  84201. this._rightjoystick.setJoystickColor("yellow");
  84202. };
  84203. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  84204. this._leftjoystick.releaseCanvas();
  84205. this._rightjoystick.releaseCanvas();
  84206. };
  84207. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  84208. return "FreeCameraVirtualJoystickInput";
  84209. };
  84210. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  84211. return "virtualJoystick";
  84212. };
  84213. return FreeCameraVirtualJoystickInput;
  84214. }());
  84215. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  84216. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  84217. })(BABYLON || (BABYLON = {}));
  84218. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  84219. "use strict";
  84220. var BABYLON;
  84221. (function (BABYLON) {
  84222. var SimplificationSettings = /** @class */ (function () {
  84223. function SimplificationSettings(quality, distance, optimizeMesh) {
  84224. this.quality = quality;
  84225. this.distance = distance;
  84226. this.optimizeMesh = optimizeMesh;
  84227. }
  84228. return SimplificationSettings;
  84229. }());
  84230. BABYLON.SimplificationSettings = SimplificationSettings;
  84231. var SimplificationQueue = /** @class */ (function () {
  84232. function SimplificationQueue() {
  84233. this.running = false;
  84234. this._simplificationArray = [];
  84235. }
  84236. SimplificationQueue.prototype.addTask = function (task) {
  84237. this._simplificationArray.push(task);
  84238. };
  84239. SimplificationQueue.prototype.executeNext = function () {
  84240. var task = this._simplificationArray.pop();
  84241. if (task) {
  84242. this.running = true;
  84243. this.runSimplification(task);
  84244. }
  84245. else {
  84246. this.running = false;
  84247. }
  84248. };
  84249. SimplificationQueue.prototype.runSimplification = function (task) {
  84250. var _this = this;
  84251. if (task.parallelProcessing) {
  84252. //parallel simplifier
  84253. task.settings.forEach(function (setting) {
  84254. var simplifier = _this.getSimplifier(task);
  84255. simplifier.simplify(setting, function (newMesh) {
  84256. task.mesh.addLODLevel(setting.distance, newMesh);
  84257. newMesh.isVisible = true;
  84258. //check if it is the last
  84259. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  84260. //all done, run the success callback.
  84261. task.successCallback();
  84262. }
  84263. _this.executeNext();
  84264. });
  84265. });
  84266. }
  84267. else {
  84268. //single simplifier.
  84269. var simplifier = this.getSimplifier(task);
  84270. var runDecimation = function (setting, callback) {
  84271. simplifier.simplify(setting, function (newMesh) {
  84272. task.mesh.addLODLevel(setting.distance, newMesh);
  84273. newMesh.isVisible = true;
  84274. //run the next quality level
  84275. callback();
  84276. });
  84277. };
  84278. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  84279. runDecimation(task.settings[loop.index], function () {
  84280. loop.executeNext();
  84281. });
  84282. }, function () {
  84283. //execution ended, run the success callback.
  84284. if (task.successCallback) {
  84285. task.successCallback();
  84286. }
  84287. _this.executeNext();
  84288. });
  84289. }
  84290. };
  84291. SimplificationQueue.prototype.getSimplifier = function (task) {
  84292. switch (task.simplificationType) {
  84293. case SimplificationType.QUADRATIC:
  84294. default:
  84295. return new QuadraticErrorSimplification(task.mesh);
  84296. }
  84297. };
  84298. return SimplificationQueue;
  84299. }());
  84300. BABYLON.SimplificationQueue = SimplificationQueue;
  84301. /**
  84302. * The implemented types of simplification.
  84303. * At the moment only Quadratic Error Decimation is implemented.
  84304. */
  84305. var SimplificationType;
  84306. (function (SimplificationType) {
  84307. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  84308. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  84309. var DecimationTriangle = /** @class */ (function () {
  84310. function DecimationTriangle(vertices) {
  84311. this.vertices = vertices;
  84312. this.error = new Array(4);
  84313. this.deleted = false;
  84314. this.isDirty = false;
  84315. this.deletePending = false;
  84316. this.borderFactor = 0;
  84317. }
  84318. return DecimationTriangle;
  84319. }());
  84320. BABYLON.DecimationTriangle = DecimationTriangle;
  84321. var DecimationVertex = /** @class */ (function () {
  84322. function DecimationVertex(position, id) {
  84323. this.position = position;
  84324. this.id = id;
  84325. this.isBorder = true;
  84326. this.q = new QuadraticMatrix();
  84327. this.triangleCount = 0;
  84328. this.triangleStart = 0;
  84329. this.originalOffsets = [];
  84330. }
  84331. DecimationVertex.prototype.updatePosition = function (newPosition) {
  84332. this.position.copyFrom(newPosition);
  84333. };
  84334. return DecimationVertex;
  84335. }());
  84336. BABYLON.DecimationVertex = DecimationVertex;
  84337. var QuadraticMatrix = /** @class */ (function () {
  84338. function QuadraticMatrix(data) {
  84339. this.data = new Array(10);
  84340. for (var i = 0; i < 10; ++i) {
  84341. if (data && data[i]) {
  84342. this.data[i] = data[i];
  84343. }
  84344. else {
  84345. this.data[i] = 0;
  84346. }
  84347. }
  84348. }
  84349. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  84350. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  84351. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  84352. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  84353. return det;
  84354. };
  84355. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  84356. for (var i = 0; i < 10; ++i) {
  84357. this.data[i] += matrix.data[i];
  84358. }
  84359. };
  84360. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  84361. for (var i = 0; i < 10; ++i) {
  84362. this.data[i] += data[i];
  84363. }
  84364. };
  84365. QuadraticMatrix.prototype.add = function (matrix) {
  84366. var m = new QuadraticMatrix();
  84367. for (var i = 0; i < 10; ++i) {
  84368. m.data[i] = this.data[i] + matrix.data[i];
  84369. }
  84370. return m;
  84371. };
  84372. QuadraticMatrix.FromData = function (a, b, c, d) {
  84373. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  84374. };
  84375. //returning an array to avoid garbage collection
  84376. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  84377. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  84378. };
  84379. return QuadraticMatrix;
  84380. }());
  84381. BABYLON.QuadraticMatrix = QuadraticMatrix;
  84382. var Reference = /** @class */ (function () {
  84383. function Reference(vertexId, triangleId) {
  84384. this.vertexId = vertexId;
  84385. this.triangleId = triangleId;
  84386. }
  84387. return Reference;
  84388. }());
  84389. BABYLON.Reference = Reference;
  84390. /**
  84391. * An implementation of the Quadratic Error simplification algorithm.
  84392. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  84393. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  84394. * @author RaananW
  84395. */
  84396. var QuadraticErrorSimplification = /** @class */ (function () {
  84397. function QuadraticErrorSimplification(_mesh) {
  84398. this._mesh = _mesh;
  84399. this.syncIterations = 5000;
  84400. this.aggressiveness = 7;
  84401. this.decimationIterations = 100;
  84402. this.boundingBoxEpsilon = BABYLON.Epsilon;
  84403. }
  84404. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  84405. var _this = this;
  84406. this.initDecimatedMesh();
  84407. //iterating through the submeshes array, one after the other.
  84408. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  84409. _this.initWithMesh(loop.index, function () {
  84410. _this.runDecimation(settings, loop.index, function () {
  84411. loop.executeNext();
  84412. });
  84413. }, settings.optimizeMesh);
  84414. }, function () {
  84415. setTimeout(function () {
  84416. successCallback(_this._reconstructedMesh);
  84417. }, 0);
  84418. });
  84419. };
  84420. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  84421. var _this = this;
  84422. var targetCount = ~~(this.triangles.length * settings.quality);
  84423. var deletedTriangles = 0;
  84424. var triangleCount = this.triangles.length;
  84425. var iterationFunction = function (iteration, callback) {
  84426. setTimeout(function () {
  84427. if (iteration % 5 === 0) {
  84428. _this.updateMesh(iteration === 0);
  84429. }
  84430. for (var i = 0; i < _this.triangles.length; ++i) {
  84431. _this.triangles[i].isDirty = false;
  84432. }
  84433. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  84434. var trianglesIterator = function (i) {
  84435. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  84436. var t = _this.triangles[tIdx];
  84437. if (!t)
  84438. return;
  84439. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  84440. return;
  84441. }
  84442. for (var j = 0; j < 3; ++j) {
  84443. if (t.error[j] < threshold) {
  84444. var deleted0 = [];
  84445. var deleted1 = [];
  84446. var v0 = t.vertices[j];
  84447. var v1 = t.vertices[(j + 1) % 3];
  84448. if (v0.isBorder || v1.isBorder)
  84449. continue;
  84450. var p = BABYLON.Vector3.Zero();
  84451. var n = BABYLON.Vector3.Zero();
  84452. var uv = BABYLON.Vector2.Zero();
  84453. var color = new BABYLON.Color4(0, 0, 0, 1);
  84454. _this.calculateError(v0, v1, p, n, uv, color);
  84455. var delTr = new Array();
  84456. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  84457. continue;
  84458. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  84459. continue;
  84460. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  84461. continue;
  84462. var uniqueArray = new Array();
  84463. delTr.forEach(function (deletedT) {
  84464. if (uniqueArray.indexOf(deletedT) === -1) {
  84465. deletedT.deletePending = true;
  84466. uniqueArray.push(deletedT);
  84467. }
  84468. });
  84469. if (uniqueArray.length % 2 !== 0) {
  84470. continue;
  84471. }
  84472. v0.q = v1.q.add(v0.q);
  84473. v0.updatePosition(p);
  84474. var tStart = _this.references.length;
  84475. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  84476. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  84477. var tCount = _this.references.length - tStart;
  84478. if (tCount <= v0.triangleCount) {
  84479. if (tCount) {
  84480. for (var c = 0; c < tCount; c++) {
  84481. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  84482. }
  84483. }
  84484. }
  84485. else {
  84486. v0.triangleStart = tStart;
  84487. }
  84488. v0.triangleCount = tCount;
  84489. break;
  84490. }
  84491. }
  84492. };
  84493. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  84494. }, 0);
  84495. };
  84496. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  84497. if (triangleCount - deletedTriangles <= targetCount)
  84498. loop.breakLoop();
  84499. else {
  84500. iterationFunction(loop.index, function () {
  84501. loop.executeNext();
  84502. });
  84503. }
  84504. }, function () {
  84505. setTimeout(function () {
  84506. //reconstruct this part of the mesh
  84507. _this.reconstructMesh(submeshIndex);
  84508. successCallback();
  84509. }, 0);
  84510. });
  84511. };
  84512. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  84513. var _this = this;
  84514. this.vertices = [];
  84515. this.triangles = [];
  84516. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  84517. var indices = this._mesh.getIndices();
  84518. var submesh = this._mesh.subMeshes[submeshIndex];
  84519. var findInVertices = function (positionToSearch) {
  84520. if (optimizeMesh) {
  84521. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  84522. if (_this.vertices[ii].position.equals(positionToSearch)) {
  84523. return _this.vertices[ii];
  84524. }
  84525. }
  84526. }
  84527. return null;
  84528. };
  84529. var vertexReferences = [];
  84530. var vertexInit = function (i) {
  84531. if (!positionData) {
  84532. return;
  84533. }
  84534. var offset = i + submesh.verticesStart;
  84535. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  84536. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  84537. vertex.originalOffsets.push(offset);
  84538. if (vertex.id === _this.vertices.length) {
  84539. _this.vertices.push(vertex);
  84540. }
  84541. vertexReferences.push(vertex.id);
  84542. };
  84543. //var totalVertices = mesh.getTotalVertices();
  84544. var totalVertices = submesh.verticesCount;
  84545. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  84546. var indicesInit = function (i) {
  84547. if (!indices) {
  84548. return;
  84549. }
  84550. var offset = (submesh.indexStart / 3) + i;
  84551. var pos = (offset * 3);
  84552. var i0 = indices[pos + 0];
  84553. var i1 = indices[pos + 1];
  84554. var i2 = indices[pos + 2];
  84555. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  84556. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  84557. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  84558. var triangle = new DecimationTriangle([v0, v1, v2]);
  84559. triangle.originalOffset = pos;
  84560. _this.triangles.push(triangle);
  84561. };
  84562. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  84563. _this.init(callback);
  84564. });
  84565. });
  84566. };
  84567. QuadraticErrorSimplification.prototype.init = function (callback) {
  84568. var _this = this;
  84569. var triangleInit1 = function (i) {
  84570. var t = _this.triangles[i];
  84571. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  84572. for (var j = 0; j < 3; j++) {
  84573. 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))));
  84574. }
  84575. };
  84576. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  84577. var triangleInit2 = function (i) {
  84578. var t = _this.triangles[i];
  84579. for (var j = 0; j < 3; ++j) {
  84580. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  84581. }
  84582. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  84583. };
  84584. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  84585. callback();
  84586. });
  84587. });
  84588. };
  84589. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  84590. var newTriangles = [];
  84591. var i;
  84592. for (i = 0; i < this.vertices.length; ++i) {
  84593. this.vertices[i].triangleCount = 0;
  84594. }
  84595. var t;
  84596. var j;
  84597. for (i = 0; i < this.triangles.length; ++i) {
  84598. if (!this.triangles[i].deleted) {
  84599. t = this.triangles[i];
  84600. for (j = 0; j < 3; ++j) {
  84601. t.vertices[j].triangleCount = 1;
  84602. }
  84603. newTriangles.push(t);
  84604. }
  84605. }
  84606. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  84607. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  84608. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  84609. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  84610. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  84611. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  84612. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  84613. var vertexCount = 0;
  84614. for (i = 0; i < this.vertices.length; ++i) {
  84615. var vertex = this.vertices[i];
  84616. vertex.id = vertexCount;
  84617. if (vertex.triangleCount) {
  84618. vertex.originalOffsets.forEach(function (originalOffset) {
  84619. if (!normalData) {
  84620. return;
  84621. }
  84622. newPositionData.push(vertex.position.x);
  84623. newPositionData.push(vertex.position.y);
  84624. newPositionData.push(vertex.position.z);
  84625. newNormalData.push(normalData[originalOffset * 3]);
  84626. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  84627. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  84628. if (uvs && uvs.length) {
  84629. newUVsData.push(uvs[(originalOffset * 2)]);
  84630. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  84631. }
  84632. else if (colorsData && colorsData.length) {
  84633. newColorsData.push(colorsData[(originalOffset * 4)]);
  84634. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  84635. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  84636. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  84637. }
  84638. ++vertexCount;
  84639. });
  84640. }
  84641. }
  84642. var startingIndex = this._reconstructedMesh.getTotalIndices();
  84643. var startingVertex = this._reconstructedMesh.getTotalVertices();
  84644. var submeshesArray = this._reconstructedMesh.subMeshes;
  84645. this._reconstructedMesh.subMeshes = [];
  84646. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  84647. var originalIndices = this._mesh.getIndices();
  84648. for (i = 0; i < newTriangles.length; ++i) {
  84649. t = newTriangles[i]; //now get the new referencing point for each vertex
  84650. [0, 1, 2].forEach(function (idx) {
  84651. var id = originalIndices[t.originalOffset + idx];
  84652. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  84653. if (offset < 0)
  84654. offset = 0;
  84655. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  84656. });
  84657. }
  84658. //overwriting the old vertex buffers and indices.
  84659. this._reconstructedMesh.setIndices(newIndicesArray);
  84660. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  84661. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  84662. if (newUVsData.length > 0)
  84663. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  84664. if (newColorsData.length > 0)
  84665. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  84666. //create submesh
  84667. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  84668. if (submeshIndex > 0) {
  84669. this._reconstructedMesh.subMeshes = [];
  84670. submeshesArray.forEach(function (submesh) {
  84671. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  84672. });
  84673. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  84674. }
  84675. };
  84676. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  84677. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  84678. this._reconstructedMesh.material = this._mesh.material;
  84679. this._reconstructedMesh.parent = this._mesh.parent;
  84680. this._reconstructedMesh.isVisible = false;
  84681. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  84682. };
  84683. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  84684. for (var i = 0; i < vertex1.triangleCount; ++i) {
  84685. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  84686. if (t.deleted)
  84687. continue;
  84688. var s = this.references[vertex1.triangleStart + i].vertexId;
  84689. var v1 = t.vertices[(s + 1) % 3];
  84690. var v2 = t.vertices[(s + 2) % 3];
  84691. if ((v1 === vertex2 || v2 === vertex2)) {
  84692. deletedArray[i] = true;
  84693. delTr.push(t);
  84694. continue;
  84695. }
  84696. var d1 = v1.position.subtract(point);
  84697. d1 = d1.normalize();
  84698. var d2 = v2.position.subtract(point);
  84699. d2 = d2.normalize();
  84700. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  84701. return true;
  84702. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  84703. deletedArray[i] = false;
  84704. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  84705. return true;
  84706. }
  84707. return false;
  84708. };
  84709. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  84710. var newDeleted = deletedTriangles;
  84711. for (var i = 0; i < vertex.triangleCount; ++i) {
  84712. var ref = this.references[vertex.triangleStart + i];
  84713. var t = this.triangles[ref.triangleId];
  84714. if (t.deleted)
  84715. continue;
  84716. if (deletedArray[i] && t.deletePending) {
  84717. t.deleted = true;
  84718. newDeleted++;
  84719. continue;
  84720. }
  84721. t.vertices[ref.vertexId] = origVertex;
  84722. t.isDirty = true;
  84723. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  84724. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  84725. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  84726. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  84727. this.references.push(ref);
  84728. }
  84729. return newDeleted;
  84730. };
  84731. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  84732. for (var i = 0; i < this.vertices.length; ++i) {
  84733. var vCount = [];
  84734. var vId = [];
  84735. var v = this.vertices[i];
  84736. var j;
  84737. for (j = 0; j < v.triangleCount; ++j) {
  84738. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  84739. for (var ii = 0; ii < 3; ii++) {
  84740. var ofs = 0;
  84741. var vv = triangle.vertices[ii];
  84742. while (ofs < vCount.length) {
  84743. if (vId[ofs] === vv.id)
  84744. break;
  84745. ++ofs;
  84746. }
  84747. if (ofs === vCount.length) {
  84748. vCount.push(1);
  84749. vId.push(vv.id);
  84750. }
  84751. else {
  84752. vCount[ofs]++;
  84753. }
  84754. }
  84755. }
  84756. for (j = 0; j < vCount.length; ++j) {
  84757. if (vCount[j] === 1) {
  84758. this.vertices[vId[j]].isBorder = true;
  84759. }
  84760. else {
  84761. this.vertices[vId[j]].isBorder = false;
  84762. }
  84763. }
  84764. }
  84765. };
  84766. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  84767. if (identifyBorders === void 0) { identifyBorders = false; }
  84768. var i;
  84769. if (!identifyBorders) {
  84770. var newTrianglesVector = [];
  84771. for (i = 0; i < this.triangles.length; ++i) {
  84772. if (!this.triangles[i].deleted) {
  84773. newTrianglesVector.push(this.triangles[i]);
  84774. }
  84775. }
  84776. this.triangles = newTrianglesVector;
  84777. }
  84778. for (i = 0; i < this.vertices.length; ++i) {
  84779. this.vertices[i].triangleCount = 0;
  84780. this.vertices[i].triangleStart = 0;
  84781. }
  84782. var t;
  84783. var j;
  84784. var v;
  84785. for (i = 0; i < this.triangles.length; ++i) {
  84786. t = this.triangles[i];
  84787. for (j = 0; j < 3; ++j) {
  84788. v = t.vertices[j];
  84789. v.triangleCount++;
  84790. }
  84791. }
  84792. var tStart = 0;
  84793. for (i = 0; i < this.vertices.length; ++i) {
  84794. this.vertices[i].triangleStart = tStart;
  84795. tStart += this.vertices[i].triangleCount;
  84796. this.vertices[i].triangleCount = 0;
  84797. }
  84798. var newReferences = new Array(this.triangles.length * 3);
  84799. for (i = 0; i < this.triangles.length; ++i) {
  84800. t = this.triangles[i];
  84801. for (j = 0; j < 3; ++j) {
  84802. v = t.vertices[j];
  84803. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  84804. v.triangleCount++;
  84805. }
  84806. }
  84807. this.references = newReferences;
  84808. if (identifyBorders) {
  84809. this.identifyBorder();
  84810. }
  84811. };
  84812. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  84813. var x = point.x;
  84814. var y = point.y;
  84815. var z = point.z;
  84816. 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
  84817. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  84818. };
  84819. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  84820. var q = vertex1.q.add(vertex2.q);
  84821. var border = vertex1.isBorder && vertex2.isBorder;
  84822. var error = 0;
  84823. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  84824. if (qDet !== 0 && !border) {
  84825. if (!pointResult) {
  84826. pointResult = BABYLON.Vector3.Zero();
  84827. }
  84828. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  84829. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  84830. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  84831. error = this.vertexError(q, pointResult);
  84832. }
  84833. else {
  84834. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  84835. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  84836. var error1 = this.vertexError(q, vertex1.position);
  84837. var error2 = this.vertexError(q, vertex2.position);
  84838. var error3 = this.vertexError(q, p3);
  84839. error = Math.min(error1, error2, error3);
  84840. if (error === error1) {
  84841. if (pointResult) {
  84842. pointResult.copyFrom(vertex1.position);
  84843. }
  84844. }
  84845. else if (error === error2) {
  84846. if (pointResult) {
  84847. pointResult.copyFrom(vertex2.position);
  84848. }
  84849. }
  84850. else {
  84851. if (pointResult) {
  84852. pointResult.copyFrom(p3);
  84853. }
  84854. }
  84855. }
  84856. return error;
  84857. };
  84858. return QuadraticErrorSimplification;
  84859. }());
  84860. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  84861. })(BABYLON || (BABYLON = {}));
  84862. //# sourceMappingURL=babylon.meshSimplification.js.map
  84863. "use strict";
  84864. var BABYLON;
  84865. (function (BABYLON) {
  84866. var MeshLODLevel = /** @class */ (function () {
  84867. function MeshLODLevel(distance, mesh) {
  84868. this.distance = distance;
  84869. this.mesh = mesh;
  84870. }
  84871. return MeshLODLevel;
  84872. }());
  84873. BABYLON.MeshLODLevel = MeshLODLevel;
  84874. })(BABYLON || (BABYLON = {}));
  84875. //# sourceMappingURL=babylon.meshLODLevel.js.map
  84876. "use strict";
  84877. var BABYLON;
  84878. (function (BABYLON) {
  84879. /**
  84880. * Defines the root class used to create scene optimization to use with SceneOptimizer
  84881. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84882. */
  84883. var SceneOptimization = /** @class */ (function () {
  84884. /**
  84885. * Creates the SceneOptimization object
  84886. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  84887. * @param desc defines the description associated with the optimization
  84888. */
  84889. function SceneOptimization(
  84890. /**
  84891. * Defines the priority of this optimization (0 by default which means first in the list)
  84892. */
  84893. priority) {
  84894. if (priority === void 0) { priority = 0; }
  84895. this.priority = priority;
  84896. }
  84897. /**
  84898. * Gets a string describing the action executed by the current optimization
  84899. * @returns description string
  84900. */
  84901. SceneOptimization.prototype.getDescription = function () {
  84902. return "";
  84903. };
  84904. /**
  84905. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84906. * @param scene defines the current scene where to apply this optimization
  84907. * @param optimizer defines the current optimizer
  84908. * @returns true if everything that can be done was applied
  84909. */
  84910. SceneOptimization.prototype.apply = function (scene, optimizer) {
  84911. return true;
  84912. };
  84913. ;
  84914. return SceneOptimization;
  84915. }());
  84916. BABYLON.SceneOptimization = SceneOptimization;
  84917. /**
  84918. * Defines an optimization used to reduce the size of render target textures
  84919. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84920. */
  84921. var TextureOptimization = /** @class */ (function (_super) {
  84922. __extends(TextureOptimization, _super);
  84923. /**
  84924. * Creates the TextureOptimization object
  84925. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  84926. * @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
  84927. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  84928. */
  84929. function TextureOptimization(
  84930. /**
  84931. * Defines the priority of this optimization (0 by default which means first in the list)
  84932. */
  84933. priority,
  84934. /**
  84935. * 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
  84936. */
  84937. maximumSize,
  84938. /**
  84939. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  84940. */
  84941. step) {
  84942. if (priority === void 0) { priority = 0; }
  84943. if (maximumSize === void 0) { maximumSize = 1024; }
  84944. if (step === void 0) { step = 0.5; }
  84945. var _this = _super.call(this, priority) || this;
  84946. _this.priority = priority;
  84947. _this.maximumSize = maximumSize;
  84948. _this.step = step;
  84949. return _this;
  84950. }
  84951. /**
  84952. * Gets a string describing the action executed by the current optimization
  84953. * @returns description string
  84954. */
  84955. TextureOptimization.prototype.getDescription = function () {
  84956. return "Reducing render target texture size to " + this.maximumSize;
  84957. };
  84958. /**
  84959. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  84960. * @param scene defines the current scene where to apply this optimization
  84961. * @param optimizer defines the current optimizer
  84962. * @returns true if everything that can be done was applied
  84963. */
  84964. TextureOptimization.prototype.apply = function (scene, optimizer) {
  84965. var allDone = true;
  84966. for (var index = 0; index < scene.textures.length; index++) {
  84967. var texture = scene.textures[index];
  84968. if (!texture.canRescale || texture.getContext) {
  84969. continue;
  84970. }
  84971. var currentSize = texture.getSize();
  84972. var maxDimension = Math.max(currentSize.width, currentSize.height);
  84973. if (maxDimension > this.maximumSize) {
  84974. texture.scale(this.step);
  84975. allDone = false;
  84976. }
  84977. }
  84978. return allDone;
  84979. };
  84980. return TextureOptimization;
  84981. }(SceneOptimization));
  84982. BABYLON.TextureOptimization = TextureOptimization;
  84983. /**
  84984. * Defines an optimization used to increase or decrease the rendering resolution
  84985. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  84986. */
  84987. var HardwareScalingOptimization = /** @class */ (function (_super) {
  84988. __extends(HardwareScalingOptimization, _super);
  84989. /**
  84990. * Creates the HardwareScalingOptimization object
  84991. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  84992. * @param maximumScale defines the maximum scale to use (2 by default)
  84993. * @param step defines the step to use between two passes (0.5 by default)
  84994. */
  84995. function HardwareScalingOptimization(
  84996. /**
  84997. * Defines the priority of this optimization (0 by default which means first in the list)
  84998. */
  84999. priority,
  85000. /**
  85001. * Defines the maximum scale to use (2 by default)
  85002. */
  85003. maximumScale,
  85004. /**
  85005. * Defines the step to use between two passes (0.5 by default)
  85006. */
  85007. step) {
  85008. if (priority === void 0) { priority = 0; }
  85009. if (maximumScale === void 0) { maximumScale = 2; }
  85010. if (step === void 0) { step = 0.25; }
  85011. var _this = _super.call(this, priority) || this;
  85012. _this.priority = priority;
  85013. _this.maximumScale = maximumScale;
  85014. _this.step = step;
  85015. _this._currentScale = -1;
  85016. _this._directionOffset = 1;
  85017. return _this;
  85018. }
  85019. /**
  85020. * Gets a string describing the action executed by the current optimization
  85021. * @return description string
  85022. */
  85023. HardwareScalingOptimization.prototype.getDescription = function () {
  85024. return "Setting hardware scaling level to " + this._currentScale;
  85025. };
  85026. /**
  85027. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85028. * @param scene defines the current scene where to apply this optimization
  85029. * @param optimizer defines the current optimizer
  85030. * @returns true if everything that can be done was applied
  85031. */
  85032. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  85033. if (this._currentScale === -1) {
  85034. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  85035. if (this._currentScale > this.maximumScale) {
  85036. this._directionOffset = -1;
  85037. }
  85038. }
  85039. this._currentScale += this._directionOffset * this.step;
  85040. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  85041. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  85042. };
  85043. ;
  85044. return HardwareScalingOptimization;
  85045. }(SceneOptimization));
  85046. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  85047. /**
  85048. * Defines an optimization used to remove shadows
  85049. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85050. */
  85051. var ShadowsOptimization = /** @class */ (function (_super) {
  85052. __extends(ShadowsOptimization, _super);
  85053. function ShadowsOptimization() {
  85054. return _super !== null && _super.apply(this, arguments) || this;
  85055. }
  85056. /**
  85057. * Gets a string describing the action executed by the current optimization
  85058. * @return description string
  85059. */
  85060. ShadowsOptimization.prototype.getDescription = function () {
  85061. return "Turning shadows on/off";
  85062. };
  85063. /**
  85064. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85065. * @param scene defines the current scene where to apply this optimization
  85066. * @param optimizer defines the current optimizer
  85067. * @returns true if everything that can be done was applied
  85068. */
  85069. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  85070. scene.shadowsEnabled = optimizer.isInImprovementMode;
  85071. return true;
  85072. };
  85073. ;
  85074. return ShadowsOptimization;
  85075. }(SceneOptimization));
  85076. BABYLON.ShadowsOptimization = ShadowsOptimization;
  85077. /**
  85078. * Defines an optimization used to turn post-processes off
  85079. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85080. */
  85081. var PostProcessesOptimization = /** @class */ (function (_super) {
  85082. __extends(PostProcessesOptimization, _super);
  85083. function PostProcessesOptimization() {
  85084. return _super !== null && _super.apply(this, arguments) || this;
  85085. }
  85086. /**
  85087. * Gets a string describing the action executed by the current optimization
  85088. * @return description string
  85089. */
  85090. PostProcessesOptimization.prototype.getDescription = function () {
  85091. return "Turning post-processes on/off";
  85092. };
  85093. /**
  85094. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85095. * @param scene defines the current scene where to apply this optimization
  85096. * @param optimizer defines the current optimizer
  85097. * @returns true if everything that can be done was applied
  85098. */
  85099. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  85100. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  85101. return true;
  85102. };
  85103. ;
  85104. return PostProcessesOptimization;
  85105. }(SceneOptimization));
  85106. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  85107. /**
  85108. * Defines an optimization used to turn lens flares off
  85109. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85110. */
  85111. var LensFlaresOptimization = /** @class */ (function (_super) {
  85112. __extends(LensFlaresOptimization, _super);
  85113. function LensFlaresOptimization() {
  85114. return _super !== null && _super.apply(this, arguments) || this;
  85115. }
  85116. /**
  85117. * Gets a string describing the action executed by the current optimization
  85118. * @return description string
  85119. */
  85120. LensFlaresOptimization.prototype.getDescription = function () {
  85121. return "Turning lens flares on/off";
  85122. };
  85123. /**
  85124. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85125. * @param scene defines the current scene where to apply this optimization
  85126. * @param optimizer defines the current optimizer
  85127. * @returns true if everything that can be done was applied
  85128. */
  85129. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  85130. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  85131. return true;
  85132. };
  85133. ;
  85134. return LensFlaresOptimization;
  85135. }(SceneOptimization));
  85136. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  85137. /**
  85138. * Defines an optimization based on user defined callback.
  85139. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85140. */
  85141. var CustomOptimization = /** @class */ (function (_super) {
  85142. __extends(CustomOptimization, _super);
  85143. function CustomOptimization() {
  85144. return _super !== null && _super.apply(this, arguments) || this;
  85145. }
  85146. /**
  85147. * Gets a string describing the action executed by the current optimization
  85148. * @returns description string
  85149. */
  85150. CustomOptimization.prototype.getDescription = function () {
  85151. if (this.onGetDescription) {
  85152. return this.onGetDescription();
  85153. }
  85154. return "Running user defined callback";
  85155. };
  85156. /**
  85157. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85158. * @param scene defines the current scene where to apply this optimization
  85159. * @param optimizer defines the current optimizer
  85160. * @returns true if everything that can be done was applied
  85161. */
  85162. CustomOptimization.prototype.apply = function (scene, optimizer) {
  85163. if (this.onApply) {
  85164. return this.onApply(scene, optimizer);
  85165. }
  85166. return true;
  85167. };
  85168. ;
  85169. return CustomOptimization;
  85170. }(SceneOptimization));
  85171. BABYLON.CustomOptimization = CustomOptimization;
  85172. /**
  85173. * Defines an optimization used to turn particles off
  85174. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85175. */
  85176. var ParticlesOptimization = /** @class */ (function (_super) {
  85177. __extends(ParticlesOptimization, _super);
  85178. function ParticlesOptimization() {
  85179. return _super !== null && _super.apply(this, arguments) || this;
  85180. }
  85181. /**
  85182. * Gets a string describing the action executed by the current optimization
  85183. * @return description string
  85184. */
  85185. ParticlesOptimization.prototype.getDescription = function () {
  85186. return "Turning particles on/off";
  85187. };
  85188. /**
  85189. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85190. * @param scene defines the current scene where to apply this optimization
  85191. * @param optimizer defines the current optimizer
  85192. * @returns true if everything that can be done was applied
  85193. */
  85194. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  85195. scene.particlesEnabled = optimizer.isInImprovementMode;
  85196. return true;
  85197. };
  85198. ;
  85199. return ParticlesOptimization;
  85200. }(SceneOptimization));
  85201. BABYLON.ParticlesOptimization = ParticlesOptimization;
  85202. /**
  85203. * Defines an optimization used to turn render targets off
  85204. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85205. */
  85206. var RenderTargetsOptimization = /** @class */ (function (_super) {
  85207. __extends(RenderTargetsOptimization, _super);
  85208. function RenderTargetsOptimization() {
  85209. return _super !== null && _super.apply(this, arguments) || this;
  85210. }
  85211. /**
  85212. * Gets a string describing the action executed by the current optimization
  85213. * @return description string
  85214. */
  85215. RenderTargetsOptimization.prototype.getDescription = function () {
  85216. return "Turning render targets off";
  85217. };
  85218. /**
  85219. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85220. * @param scene defines the current scene where to apply this optimization
  85221. * @param optimizer defines the current optimizer
  85222. * @returns true if everything that can be done was applied
  85223. */
  85224. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  85225. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  85226. return true;
  85227. };
  85228. ;
  85229. return RenderTargetsOptimization;
  85230. }(SceneOptimization));
  85231. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  85232. /**
  85233. * Defines an optimization used to merge meshes with compatible materials
  85234. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85235. */
  85236. var MergeMeshesOptimization = /** @class */ (function (_super) {
  85237. __extends(MergeMeshesOptimization, _super);
  85238. function MergeMeshesOptimization() {
  85239. var _this = _super !== null && _super.apply(this, arguments) || this;
  85240. _this._canBeMerged = function (abstractMesh) {
  85241. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  85242. return false;
  85243. }
  85244. var mesh = abstractMesh;
  85245. if (!mesh.isVisible || !mesh.isEnabled()) {
  85246. return false;
  85247. }
  85248. if (mesh.instances.length > 0) {
  85249. return false;
  85250. }
  85251. if (mesh.skeleton || mesh.hasLODLevels) {
  85252. return false;
  85253. }
  85254. if (mesh.parent) {
  85255. return false;
  85256. }
  85257. return true;
  85258. };
  85259. return _this;
  85260. }
  85261. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  85262. /**
  85263. * Gets or sets a boolean which defines if optimization octree has to be updated
  85264. */
  85265. get: function () {
  85266. return MergeMeshesOptimization._UpdateSelectionTree;
  85267. },
  85268. /**
  85269. * Gets or sets a boolean which defines if optimization octree has to be updated
  85270. */
  85271. set: function (value) {
  85272. MergeMeshesOptimization._UpdateSelectionTree = value;
  85273. },
  85274. enumerable: true,
  85275. configurable: true
  85276. });
  85277. /**
  85278. * Gets a string describing the action executed by the current optimization
  85279. * @return description string
  85280. */
  85281. MergeMeshesOptimization.prototype.getDescription = function () {
  85282. return "Merging similar meshes together";
  85283. };
  85284. /**
  85285. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  85286. * @param scene defines the current scene where to apply this optimization
  85287. * @param optimizer defines the current optimizer
  85288. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  85289. * @returns true if everything that can be done was applied
  85290. */
  85291. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  85292. var globalPool = scene.meshes.slice(0);
  85293. var globalLength = globalPool.length;
  85294. for (var index = 0; index < globalLength; index++) {
  85295. var currentPool = new Array();
  85296. var current = globalPool[index];
  85297. // Checks
  85298. if (!this._canBeMerged(current)) {
  85299. continue;
  85300. }
  85301. currentPool.push(current);
  85302. // Find compatible meshes
  85303. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  85304. var otherMesh = globalPool[subIndex];
  85305. if (!this._canBeMerged(otherMesh)) {
  85306. continue;
  85307. }
  85308. if (otherMesh.material !== current.material) {
  85309. continue;
  85310. }
  85311. if (otherMesh.checkCollisions !== current.checkCollisions) {
  85312. continue;
  85313. }
  85314. currentPool.push(otherMesh);
  85315. globalLength--;
  85316. globalPool.splice(subIndex, 1);
  85317. subIndex--;
  85318. }
  85319. if (currentPool.length < 2) {
  85320. continue;
  85321. }
  85322. // Merge meshes
  85323. BABYLON.Mesh.MergeMeshes(currentPool);
  85324. }
  85325. if (updateSelectionTree != undefined) {
  85326. if (updateSelectionTree) {
  85327. scene.createOrUpdateSelectionOctree();
  85328. }
  85329. }
  85330. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  85331. scene.createOrUpdateSelectionOctree();
  85332. }
  85333. return true;
  85334. };
  85335. ;
  85336. MergeMeshesOptimization._UpdateSelectionTree = false;
  85337. return MergeMeshesOptimization;
  85338. }(SceneOptimization));
  85339. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  85340. /**
  85341. * Defines a list of options used by SceneOptimizer
  85342. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85343. */
  85344. var SceneOptimizerOptions = /** @class */ (function () {
  85345. /**
  85346. * Creates a new list of options used by SceneOptimizer
  85347. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  85348. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  85349. */
  85350. function SceneOptimizerOptions(
  85351. /**
  85352. * Defines the target frame rate to reach (60 by default)
  85353. */
  85354. targetFrameRate,
  85355. /**
  85356. * Defines the interval between two checkes (2000ms by default)
  85357. */
  85358. trackerDuration) {
  85359. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  85360. if (trackerDuration === void 0) { trackerDuration = 2000; }
  85361. this.targetFrameRate = targetFrameRate;
  85362. this.trackerDuration = trackerDuration;
  85363. /**
  85364. * Gets the list of optimizations to apply
  85365. */
  85366. this.optimizations = new Array();
  85367. }
  85368. /**
  85369. * Add a new optimization
  85370. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  85371. * @returns the current SceneOptimizerOptions
  85372. */
  85373. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  85374. this.optimizations.push(optimization);
  85375. return this;
  85376. };
  85377. /**
  85378. * Add a new custom optimization
  85379. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  85380. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  85381. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  85382. * @returns the current SceneOptimizerOptions
  85383. */
  85384. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  85385. if (priority === void 0) { priority = 0; }
  85386. var optimization = new CustomOptimization(priority);
  85387. optimization.onApply = onApply;
  85388. optimization.onGetDescription = onGetDescription;
  85389. this.optimizations.push(optimization);
  85390. return this;
  85391. };
  85392. /**
  85393. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  85394. * @param targetFrameRate defines the target frame rate (60 by default)
  85395. * @returns a SceneOptimizerOptions object
  85396. */
  85397. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  85398. var result = new SceneOptimizerOptions(targetFrameRate);
  85399. var priority = 0;
  85400. result.addOptimization(new MergeMeshesOptimization(priority));
  85401. result.addOptimization(new ShadowsOptimization(priority));
  85402. result.addOptimization(new LensFlaresOptimization(priority));
  85403. // Next priority
  85404. priority++;
  85405. result.addOptimization(new PostProcessesOptimization(priority));
  85406. result.addOptimization(new ParticlesOptimization(priority));
  85407. // Next priority
  85408. priority++;
  85409. result.addOptimization(new TextureOptimization(priority, 1024));
  85410. return result;
  85411. };
  85412. /**
  85413. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  85414. * @param targetFrameRate defines the target frame rate (60 by default)
  85415. * @returns a SceneOptimizerOptions object
  85416. */
  85417. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  85418. var result = new SceneOptimizerOptions(targetFrameRate);
  85419. var priority = 0;
  85420. result.addOptimization(new MergeMeshesOptimization(priority));
  85421. result.addOptimization(new ShadowsOptimization(priority));
  85422. result.addOptimization(new LensFlaresOptimization(priority));
  85423. // Next priority
  85424. priority++;
  85425. result.addOptimization(new PostProcessesOptimization(priority));
  85426. result.addOptimization(new ParticlesOptimization(priority));
  85427. // Next priority
  85428. priority++;
  85429. result.addOptimization(new TextureOptimization(priority, 512));
  85430. // Next priority
  85431. priority++;
  85432. result.addOptimization(new RenderTargetsOptimization(priority));
  85433. // Next priority
  85434. priority++;
  85435. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  85436. return result;
  85437. };
  85438. /**
  85439. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  85440. * @param targetFrameRate defines the target frame rate (60 by default)
  85441. * @returns a SceneOptimizerOptions object
  85442. */
  85443. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  85444. var result = new SceneOptimizerOptions(targetFrameRate);
  85445. var priority = 0;
  85446. result.addOptimization(new MergeMeshesOptimization(priority));
  85447. result.addOptimization(new ShadowsOptimization(priority));
  85448. result.addOptimization(new LensFlaresOptimization(priority));
  85449. // Next priority
  85450. priority++;
  85451. result.addOptimization(new PostProcessesOptimization(priority));
  85452. result.addOptimization(new ParticlesOptimization(priority));
  85453. // Next priority
  85454. priority++;
  85455. result.addOptimization(new TextureOptimization(priority, 256));
  85456. // Next priority
  85457. priority++;
  85458. result.addOptimization(new RenderTargetsOptimization(priority));
  85459. // Next priority
  85460. priority++;
  85461. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  85462. return result;
  85463. };
  85464. return SceneOptimizerOptions;
  85465. }());
  85466. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  85467. /**
  85468. * Class used to run optimizations in order to reach a target frame rate
  85469. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  85470. */
  85471. var SceneOptimizer = /** @class */ (function () {
  85472. /**
  85473. * Creates a new SceneOptimizer
  85474. * @param scene defines the scene to work on
  85475. * @param options defines the options to use with the SceneOptimizer
  85476. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  85477. * @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)
  85478. */
  85479. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  85480. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  85481. if (improvementMode === void 0) { improvementMode = false; }
  85482. var _this = this;
  85483. this._isRunning = false;
  85484. this._currentPriorityLevel = 0;
  85485. this._targetFrameRate = 60;
  85486. this._trackerDuration = 2000;
  85487. this._currentFrameRate = 0;
  85488. this._improvementMode = false;
  85489. /**
  85490. * Defines an observable called when the optimizer reaches the target frame rate
  85491. */
  85492. this.onSuccessObservable = new BABYLON.Observable();
  85493. /**
  85494. * Defines an observable called when the optimizer enables an optimization
  85495. */
  85496. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  85497. /**
  85498. * Defines an observable called when the optimizer is not able to reach the target frame rate
  85499. */
  85500. this.onFailureObservable = new BABYLON.Observable();
  85501. if (!options) {
  85502. this._options = new SceneOptimizerOptions();
  85503. }
  85504. else {
  85505. this._options = options;
  85506. }
  85507. if (this._options.targetFrameRate) {
  85508. this._targetFrameRate = this._options.targetFrameRate;
  85509. }
  85510. if (this._options.trackerDuration) {
  85511. this._trackerDuration = this._options.trackerDuration;
  85512. }
  85513. if (autoGeneratePriorities) {
  85514. var priority = 0;
  85515. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  85516. var optim = _a[_i];
  85517. optim.priority = priority++;
  85518. }
  85519. }
  85520. this._improvementMode = improvementMode;
  85521. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85522. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  85523. _this._sceneDisposeObserver = null;
  85524. _this.dispose();
  85525. });
  85526. }
  85527. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  85528. /**
  85529. * Gets a boolean indicating if the optimizer is in improvement mode
  85530. */
  85531. get: function () {
  85532. return this._improvementMode;
  85533. },
  85534. enumerable: true,
  85535. configurable: true
  85536. });
  85537. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  85538. /**
  85539. * Gets the current priority level (0 at start)
  85540. */
  85541. get: function () {
  85542. return this._currentPriorityLevel;
  85543. },
  85544. enumerable: true,
  85545. configurable: true
  85546. });
  85547. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  85548. /**
  85549. * Gets the current frame rate checked by the SceneOptimizer
  85550. */
  85551. get: function () {
  85552. return this._currentFrameRate;
  85553. },
  85554. enumerable: true,
  85555. configurable: true
  85556. });
  85557. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  85558. /**
  85559. * Gets or sets the current target frame rate (60 by default)
  85560. */
  85561. get: function () {
  85562. return this._targetFrameRate;
  85563. },
  85564. /**
  85565. * Gets or sets the current target frame rate (60 by default)
  85566. */
  85567. set: function (value) {
  85568. this._targetFrameRate = value;
  85569. },
  85570. enumerable: true,
  85571. configurable: true
  85572. });
  85573. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  85574. /**
  85575. * Gets or sets the current interval between two checks (every 2000ms by default)
  85576. */
  85577. get: function () {
  85578. return this._trackerDuration;
  85579. },
  85580. /**
  85581. * Gets or sets the current interval between two checks (every 2000ms by default)
  85582. */
  85583. set: function (value) {
  85584. this._trackerDuration = value;
  85585. },
  85586. enumerable: true,
  85587. configurable: true
  85588. });
  85589. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  85590. /**
  85591. * Gets the list of active optimizations
  85592. */
  85593. get: function () {
  85594. return this._options.optimizations;
  85595. },
  85596. enumerable: true,
  85597. configurable: true
  85598. });
  85599. /**
  85600. * Stops the current optimizer
  85601. */
  85602. SceneOptimizer.prototype.stop = function () {
  85603. this._isRunning = false;
  85604. };
  85605. /**
  85606. * Reset the optimizer to initial step (current priority level = 0)
  85607. */
  85608. SceneOptimizer.prototype.reset = function () {
  85609. this._currentPriorityLevel = 0;
  85610. };
  85611. /**
  85612. * Start the optimizer. By default it will try to reach a specific framerate
  85613. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  85614. */
  85615. SceneOptimizer.prototype.start = function () {
  85616. var _this = this;
  85617. if (this._isRunning) {
  85618. return;
  85619. }
  85620. this._isRunning = true;
  85621. // Let's wait for the scene to be ready before running our check
  85622. this._scene.executeWhenReady(function () {
  85623. setTimeout(function () {
  85624. _this._checkCurrentState();
  85625. }, _this._trackerDuration);
  85626. });
  85627. };
  85628. SceneOptimizer.prototype._checkCurrentState = function () {
  85629. var _this = this;
  85630. if (!this._isRunning) {
  85631. return;
  85632. }
  85633. var scene = this._scene;
  85634. var options = this._options;
  85635. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  85636. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  85637. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  85638. this._isRunning = false;
  85639. this.onSuccessObservable.notifyObservers(this);
  85640. return;
  85641. }
  85642. // Apply current level of optimizations
  85643. var allDone = true;
  85644. var noOptimizationApplied = true;
  85645. for (var index = 0; index < options.optimizations.length; index++) {
  85646. var optimization = options.optimizations[index];
  85647. if (optimization.priority === this._currentPriorityLevel) {
  85648. noOptimizationApplied = false;
  85649. allDone = allDone && optimization.apply(scene, this);
  85650. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  85651. }
  85652. }
  85653. // If no optimization was applied, this is a failure :(
  85654. if (noOptimizationApplied) {
  85655. this._isRunning = false;
  85656. this.onFailureObservable.notifyObservers(this);
  85657. return;
  85658. }
  85659. // If all optimizations were done, move to next level
  85660. if (allDone) {
  85661. this._currentPriorityLevel++;
  85662. }
  85663. // Let's the system running for a specific amount of time before checking FPS
  85664. scene.executeWhenReady(function () {
  85665. setTimeout(function () {
  85666. _this._checkCurrentState();
  85667. }, _this._trackerDuration);
  85668. });
  85669. };
  85670. /**
  85671. * Release all resources
  85672. */
  85673. SceneOptimizer.prototype.dispose = function () {
  85674. this.stop();
  85675. this.onSuccessObservable.clear();
  85676. this.onFailureObservable.clear();
  85677. this.onNewOptimizationAppliedObservable.clear();
  85678. if (this._sceneDisposeObserver) {
  85679. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  85680. }
  85681. };
  85682. /**
  85683. * Helper function to create a SceneOptimizer with one single line of code
  85684. * @param scene defines the scene to work on
  85685. * @param options defines the options to use with the SceneOptimizer
  85686. * @param onSuccess defines a callback to call on success
  85687. * @param onFailure defines a callback to call on failure
  85688. * @returns the new SceneOptimizer object
  85689. */
  85690. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  85691. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  85692. if (onSuccess) {
  85693. optimizer.onSuccessObservable.add(function () {
  85694. onSuccess();
  85695. });
  85696. }
  85697. if (onFailure) {
  85698. optimizer.onFailureObservable.add(function () {
  85699. onFailure();
  85700. });
  85701. }
  85702. optimizer.start();
  85703. return optimizer;
  85704. };
  85705. return SceneOptimizer;
  85706. }());
  85707. BABYLON.SceneOptimizer = SceneOptimizer;
  85708. })(BABYLON || (BABYLON = {}));
  85709. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  85710. "use strict";
  85711. var BABYLON;
  85712. (function (BABYLON) {
  85713. var OutlineRenderer = /** @class */ (function () {
  85714. function OutlineRenderer(scene) {
  85715. this.zOffset = 1;
  85716. this._scene = scene;
  85717. }
  85718. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  85719. var _this = this;
  85720. if (useOverlay === void 0) { useOverlay = false; }
  85721. var scene = this._scene;
  85722. var engine = this._scene.getEngine();
  85723. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  85724. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  85725. return;
  85726. }
  85727. var mesh = subMesh.getRenderingMesh();
  85728. var material = subMesh.getMaterial();
  85729. if (!material || !scene.activeCamera) {
  85730. return;
  85731. }
  85732. engine.enableEffect(this._effect);
  85733. // Logarithmic depth
  85734. if (material.useLogarithmicDepth) {
  85735. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  85736. }
  85737. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  85738. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  85739. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  85740. // Bones
  85741. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  85742. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  85743. }
  85744. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  85745. // Alpha test
  85746. if (material && material.needAlphaTesting()) {
  85747. var alphaTexture = material.getAlphaTestTexture();
  85748. if (alphaTexture) {
  85749. this._effect.setTexture("diffuseSampler", alphaTexture);
  85750. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  85751. }
  85752. }
  85753. engine.setZOffset(-this.zOffset);
  85754. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  85755. engine.setZOffset(0);
  85756. };
  85757. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  85758. var defines = [];
  85759. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  85760. var mesh = subMesh.getMesh();
  85761. var material = subMesh.getMaterial();
  85762. if (material) {
  85763. // Alpha test
  85764. if (material.needAlphaTesting()) {
  85765. defines.push("#define ALPHATEST");
  85766. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  85767. attribs.push(BABYLON.VertexBuffer.UVKind);
  85768. defines.push("#define UV1");
  85769. }
  85770. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  85771. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  85772. defines.push("#define UV2");
  85773. }
  85774. }
  85775. //Logarithmic depth
  85776. if (material.useLogarithmicDepth) {
  85777. defines.push("#define LOGARITHMICDEPTH");
  85778. }
  85779. }
  85780. // Bones
  85781. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  85782. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  85783. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  85784. if (mesh.numBoneInfluencers > 4) {
  85785. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  85786. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  85787. }
  85788. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  85789. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  85790. }
  85791. else {
  85792. defines.push("#define NUM_BONE_INFLUENCERS 0");
  85793. }
  85794. // Instances
  85795. if (useInstances) {
  85796. defines.push("#define INSTANCES");
  85797. attribs.push("world0");
  85798. attribs.push("world1");
  85799. attribs.push("world2");
  85800. attribs.push("world3");
  85801. }
  85802. // Get correct effect
  85803. var join = defines.join("\n");
  85804. if (this._cachedDefines !== join) {
  85805. this._cachedDefines = join;
  85806. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  85807. }
  85808. return this._effect.isReady();
  85809. };
  85810. return OutlineRenderer;
  85811. }());
  85812. BABYLON.OutlineRenderer = OutlineRenderer;
  85813. })(BABYLON || (BABYLON = {}));
  85814. //# sourceMappingURL=babylon.outlineRenderer.js.map
  85815. "use strict";
  85816. var BABYLON;
  85817. (function (BABYLON) {
  85818. var FaceAdjacencies = /** @class */ (function () {
  85819. function FaceAdjacencies() {
  85820. this.edges = new Array();
  85821. this.edgesConnectedCount = 0;
  85822. }
  85823. return FaceAdjacencies;
  85824. }());
  85825. var EdgesRenderer = /** @class */ (function () {
  85826. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  85827. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  85828. if (epsilon === void 0) { epsilon = 0.95; }
  85829. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  85830. this.edgesWidthScalerForOrthographic = 1000.0;
  85831. this.edgesWidthScalerForPerspective = 50.0;
  85832. this._linesPositions = new Array();
  85833. this._linesNormals = new Array();
  85834. this._linesIndices = new Array();
  85835. this._buffers = {};
  85836. this._checkVerticesInsteadOfIndices = false;
  85837. this._source = source;
  85838. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  85839. this._epsilon = epsilon;
  85840. this._prepareRessources();
  85841. this._generateEdgesLines();
  85842. }
  85843. EdgesRenderer.prototype._prepareRessources = function () {
  85844. if (this._lineShader) {
  85845. return;
  85846. }
  85847. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  85848. attributes: ["position", "normal"],
  85849. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  85850. });
  85851. this._lineShader.disableDepthWrite = true;
  85852. this._lineShader.backFaceCulling = false;
  85853. };
  85854. EdgesRenderer.prototype._rebuild = function () {
  85855. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  85856. if (buffer) {
  85857. buffer._rebuild();
  85858. }
  85859. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  85860. if (buffer) {
  85861. buffer._rebuild();
  85862. }
  85863. var scene = this._source.getScene();
  85864. var engine = scene.getEngine();
  85865. this._ib = engine.createIndexBuffer(this._linesIndices);
  85866. };
  85867. EdgesRenderer.prototype.dispose = function () {
  85868. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  85869. if (buffer) {
  85870. buffer.dispose();
  85871. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  85872. }
  85873. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  85874. if (buffer) {
  85875. buffer.dispose();
  85876. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  85877. }
  85878. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  85879. this._lineShader.dispose();
  85880. };
  85881. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  85882. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  85883. return 0;
  85884. }
  85885. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  85886. return 1;
  85887. }
  85888. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  85889. return 2;
  85890. }
  85891. return -1;
  85892. };
  85893. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  85894. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  85895. return 0;
  85896. }
  85897. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  85898. return 1;
  85899. }
  85900. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  85901. return 2;
  85902. }
  85903. return -1;
  85904. };
  85905. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  85906. var needToCreateLine;
  85907. if (edge === undefined) {
  85908. needToCreateLine = true;
  85909. }
  85910. else {
  85911. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  85912. needToCreateLine = dotProduct < this._epsilon;
  85913. }
  85914. if (needToCreateLine) {
  85915. var offset = this._linesPositions.length / 3;
  85916. var normal = p0.subtract(p1);
  85917. normal.normalize();
  85918. // Positions
  85919. this._linesPositions.push(p0.x);
  85920. this._linesPositions.push(p0.y);
  85921. this._linesPositions.push(p0.z);
  85922. this._linesPositions.push(p0.x);
  85923. this._linesPositions.push(p0.y);
  85924. this._linesPositions.push(p0.z);
  85925. this._linesPositions.push(p1.x);
  85926. this._linesPositions.push(p1.y);
  85927. this._linesPositions.push(p1.z);
  85928. this._linesPositions.push(p1.x);
  85929. this._linesPositions.push(p1.y);
  85930. this._linesPositions.push(p1.z);
  85931. // Normals
  85932. this._linesNormals.push(p1.x);
  85933. this._linesNormals.push(p1.y);
  85934. this._linesNormals.push(p1.z);
  85935. this._linesNormals.push(-1);
  85936. this._linesNormals.push(p1.x);
  85937. this._linesNormals.push(p1.y);
  85938. this._linesNormals.push(p1.z);
  85939. this._linesNormals.push(1);
  85940. this._linesNormals.push(p0.x);
  85941. this._linesNormals.push(p0.y);
  85942. this._linesNormals.push(p0.z);
  85943. this._linesNormals.push(-1);
  85944. this._linesNormals.push(p0.x);
  85945. this._linesNormals.push(p0.y);
  85946. this._linesNormals.push(p0.z);
  85947. this._linesNormals.push(1);
  85948. // Indices
  85949. this._linesIndices.push(offset);
  85950. this._linesIndices.push(offset + 1);
  85951. this._linesIndices.push(offset + 2);
  85952. this._linesIndices.push(offset);
  85953. this._linesIndices.push(offset + 2);
  85954. this._linesIndices.push(offset + 3);
  85955. }
  85956. };
  85957. EdgesRenderer.prototype._generateEdgesLines = function () {
  85958. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  85959. var indices = this._source.getIndices();
  85960. if (!indices || !positions) {
  85961. return;
  85962. }
  85963. // First let's find adjacencies
  85964. var adjacencies = new Array();
  85965. var faceNormals = new Array();
  85966. var index;
  85967. var faceAdjacencies;
  85968. // Prepare faces
  85969. for (index = 0; index < indices.length; index += 3) {
  85970. faceAdjacencies = new FaceAdjacencies();
  85971. var p0Index = indices[index];
  85972. var p1Index = indices[index + 1];
  85973. var p2Index = indices[index + 2];
  85974. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  85975. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  85976. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  85977. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  85978. faceNormal.normalize();
  85979. faceNormals.push(faceNormal);
  85980. adjacencies.push(faceAdjacencies);
  85981. }
  85982. // Scan
  85983. for (index = 0; index < adjacencies.length; index++) {
  85984. faceAdjacencies = adjacencies[index];
  85985. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  85986. var otherFaceAdjacencies = adjacencies[otherIndex];
  85987. if (faceAdjacencies.edgesConnectedCount === 3) {
  85988. break;
  85989. }
  85990. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  85991. continue;
  85992. }
  85993. var otherP0 = indices[otherIndex * 3];
  85994. var otherP1 = indices[otherIndex * 3 + 1];
  85995. var otherP2 = indices[otherIndex * 3 + 2];
  85996. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  85997. var otherEdgeIndex = 0;
  85998. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  85999. continue;
  86000. }
  86001. switch (edgeIndex) {
  86002. case 0:
  86003. if (this._checkVerticesInsteadOfIndices) {
  86004. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  86005. }
  86006. else {
  86007. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  86008. }
  86009. break;
  86010. case 1:
  86011. if (this._checkVerticesInsteadOfIndices) {
  86012. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  86013. }
  86014. else {
  86015. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  86016. }
  86017. break;
  86018. case 2:
  86019. if (this._checkVerticesInsteadOfIndices) {
  86020. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  86021. }
  86022. else {
  86023. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  86024. }
  86025. break;
  86026. }
  86027. if (otherEdgeIndex === -1) {
  86028. continue;
  86029. }
  86030. faceAdjacencies.edges[edgeIndex] = otherIndex;
  86031. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  86032. faceAdjacencies.edgesConnectedCount++;
  86033. otherFaceAdjacencies.edgesConnectedCount++;
  86034. if (faceAdjacencies.edgesConnectedCount === 3) {
  86035. break;
  86036. }
  86037. }
  86038. }
  86039. }
  86040. // Create lines
  86041. for (index = 0; index < adjacencies.length; index++) {
  86042. // 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
  86043. var current = adjacencies[index];
  86044. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  86045. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  86046. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  86047. }
  86048. // Merge into a single mesh
  86049. var engine = this._source.getScene().getEngine();
  86050. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  86051. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  86052. this._ib = engine.createIndexBuffer(this._linesIndices);
  86053. this._indicesCount = this._linesIndices.length;
  86054. };
  86055. EdgesRenderer.prototype.render = function () {
  86056. var scene = this._source.getScene();
  86057. if (!this._lineShader.isReady() || !scene.activeCamera) {
  86058. return;
  86059. }
  86060. var engine = scene.getEngine();
  86061. this._lineShader._preBind();
  86062. // VBOs
  86063. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  86064. scene.resetCachedMaterial();
  86065. this._lineShader.setColor4("color", this._source.edgesColor);
  86066. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  86067. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  86068. }
  86069. else {
  86070. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  86071. }
  86072. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  86073. this._lineShader.bind(this._source.getWorldMatrix());
  86074. // Draw order
  86075. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  86076. this._lineShader.unbind();
  86077. engine.setDepthWrite(true);
  86078. };
  86079. return EdgesRenderer;
  86080. }());
  86081. BABYLON.EdgesRenderer = EdgesRenderer;
  86082. })(BABYLON || (BABYLON = {}));
  86083. //# sourceMappingURL=babylon.edgesRenderer.js.map
  86084. "use strict";
  86085. var __assign = (this && this.__assign) || Object.assign || function(t) {
  86086. for (var s, i = 1, n = arguments.length; i < n; i++) {
  86087. s = arguments[i];
  86088. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  86089. t[p] = s[p];
  86090. }
  86091. return t;
  86092. };
  86093. var BABYLON;
  86094. (function (BABYLON) {
  86095. /**
  86096. * The effect layer Helps adding post process effect blended with the main pass.
  86097. *
  86098. * This can be for instance use to generate glow or higlight effects on the scene.
  86099. *
  86100. * The effect layer class can not be used directly and is intented to inherited from to be
  86101. * customized per effects.
  86102. */
  86103. var EffectLayer = /** @class */ (function () {
  86104. /**
  86105. * Instantiates a new effect Layer and references it in the scene.
  86106. * @param name The name of the layer
  86107. * @param scene The scene to use the layer in
  86108. */
  86109. function EffectLayer(
  86110. /** The Friendly of the effect in the scene */
  86111. name, scene) {
  86112. this.name = name;
  86113. this._vertexBuffers = {};
  86114. this._maxSize = 0;
  86115. this._mainTextureDesiredSize = { width: 0, height: 0 };
  86116. this._shouldRender = true;
  86117. this._postProcesses = [];
  86118. this._textures = [];
  86119. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  86120. /**
  86121. * The clear color of the texture used to generate the glow map.
  86122. */
  86123. this.neutralColor = new BABYLON.Color4();
  86124. /**
  86125. * Specifies wether the highlight layer is enabled or not.
  86126. */
  86127. this.isEnabled = true;
  86128. /**
  86129. * An event triggered when the effect layer has been disposed.
  86130. */
  86131. this.onDisposeObservable = new BABYLON.Observable();
  86132. /**
  86133. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  86134. */
  86135. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  86136. /**
  86137. * An event triggered when the generated texture is being merged in the scene.
  86138. */
  86139. this.onBeforeComposeObservable = new BABYLON.Observable();
  86140. /**
  86141. * An event triggered when the generated texture has been merged in the scene.
  86142. */
  86143. this.onAfterComposeObservable = new BABYLON.Observable();
  86144. /**
  86145. * An event triggered when the efffect layer changes its size.
  86146. */
  86147. this.onSizeChangedObservable = new BABYLON.Observable();
  86148. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  86149. this._engine = scene.getEngine();
  86150. this._maxSize = this._engine.getCaps().maxTextureSize;
  86151. this._scene.effectLayers.push(this);
  86152. // Generate Buffers
  86153. this._generateIndexBuffer();
  86154. this._genrateVertexBuffer();
  86155. }
  86156. Object.defineProperty(EffectLayer.prototype, "camera", {
  86157. /**
  86158. * Gets the camera attached to the layer.
  86159. */
  86160. get: function () {
  86161. return this._effectLayerOptions.camera;
  86162. },
  86163. enumerable: true,
  86164. configurable: true
  86165. });
  86166. /**
  86167. * Initializes the effect layer with the required options.
  86168. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  86169. */
  86170. EffectLayer.prototype._init = function (options) {
  86171. // Adapt options
  86172. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  86173. this._setMainTextureSize();
  86174. this._createMainTexture();
  86175. this._createTextureAndPostProcesses();
  86176. this._mergeEffect = this._createMergeEffect();
  86177. };
  86178. /**
  86179. * Generates the index buffer of the full screen quad blending to the main canvas.
  86180. */
  86181. EffectLayer.prototype._generateIndexBuffer = function () {
  86182. // Indices
  86183. var indices = [];
  86184. indices.push(0);
  86185. indices.push(1);
  86186. indices.push(2);
  86187. indices.push(0);
  86188. indices.push(2);
  86189. indices.push(3);
  86190. this._indexBuffer = this._engine.createIndexBuffer(indices);
  86191. };
  86192. /**
  86193. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  86194. */
  86195. EffectLayer.prototype._genrateVertexBuffer = function () {
  86196. // VBO
  86197. var vertices = [];
  86198. vertices.push(1, 1);
  86199. vertices.push(-1, 1);
  86200. vertices.push(-1, -1);
  86201. vertices.push(1, -1);
  86202. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  86203. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  86204. };
  86205. /**
  86206. * Sets the main texture desired size which is the closest power of two
  86207. * of the engine canvas size.
  86208. */
  86209. EffectLayer.prototype._setMainTextureSize = function () {
  86210. if (this._effectLayerOptions.mainTextureFixedSize) {
  86211. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  86212. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  86213. }
  86214. else {
  86215. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  86216. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  86217. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  86218. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  86219. }
  86220. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  86221. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  86222. };
  86223. /**
  86224. * Creates the main texture for the effect layer.
  86225. */
  86226. EffectLayer.prototype._createMainTexture = function () {
  86227. var _this = this;
  86228. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  86229. width: this._mainTextureDesiredSize.width,
  86230. height: this._mainTextureDesiredSize.height
  86231. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  86232. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  86233. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86234. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86235. this._mainTexture.anisotropicFilteringLevel = 1;
  86236. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  86237. this._mainTexture.renderParticles = false;
  86238. this._mainTexture.renderList = null;
  86239. this._mainTexture.ignoreCameraViewport = true;
  86240. // Custom render function
  86241. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  86242. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  86243. var index;
  86244. var engine = _this._scene.getEngine();
  86245. if (depthOnlySubMeshes.length) {
  86246. engine.setColorWrite(false);
  86247. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  86248. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  86249. }
  86250. engine.setColorWrite(true);
  86251. }
  86252. for (index = 0; index < opaqueSubMeshes.length; index++) {
  86253. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  86254. }
  86255. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  86256. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  86257. }
  86258. for (index = 0; index < transparentSubMeshes.length; index++) {
  86259. _this._renderSubMesh(transparentSubMeshes.data[index]);
  86260. }
  86261. };
  86262. this._mainTexture.onClearObservable.add(function (engine) {
  86263. engine.clear(_this.neutralColor, true, true, true);
  86264. });
  86265. };
  86266. /**
  86267. * Checks for the readiness of the element composing the layer.
  86268. * @param subMesh the mesh to check for
  86269. * @param useInstances specify wether or not to use instances to render the mesh
  86270. * @param emissiveTexture the associated emissive texture used to generate the glow
  86271. * @return true if ready otherwise, false
  86272. */
  86273. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  86274. var material = subMesh.getMaterial();
  86275. if (!material) {
  86276. return false;
  86277. }
  86278. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  86279. return false;
  86280. }
  86281. var defines = [];
  86282. var attribs = [BABYLON.VertexBuffer.PositionKind];
  86283. var mesh = subMesh.getMesh();
  86284. var uv1 = false;
  86285. var uv2 = false;
  86286. // Alpha test
  86287. if (material && material.needAlphaTesting()) {
  86288. var alphaTexture = material.getAlphaTestTexture();
  86289. if (alphaTexture) {
  86290. defines.push("#define ALPHATEST");
  86291. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  86292. alphaTexture.coordinatesIndex === 1) {
  86293. defines.push("#define DIFFUSEUV2");
  86294. uv2 = true;
  86295. }
  86296. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  86297. defines.push("#define DIFFUSEUV1");
  86298. uv1 = true;
  86299. }
  86300. }
  86301. }
  86302. // Emissive
  86303. if (emissiveTexture) {
  86304. defines.push("#define EMISSIVE");
  86305. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  86306. emissiveTexture.coordinatesIndex === 1) {
  86307. defines.push("#define EMISSIVEUV2");
  86308. uv2 = true;
  86309. }
  86310. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  86311. defines.push("#define EMISSIVEUV1");
  86312. uv1 = true;
  86313. }
  86314. }
  86315. if (uv1) {
  86316. attribs.push(BABYLON.VertexBuffer.UVKind);
  86317. defines.push("#define UV1");
  86318. }
  86319. if (uv2) {
  86320. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  86321. defines.push("#define UV2");
  86322. }
  86323. // Bones
  86324. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  86325. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  86326. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  86327. if (mesh.numBoneInfluencers > 4) {
  86328. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  86329. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  86330. }
  86331. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  86332. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  86333. }
  86334. else {
  86335. defines.push("#define NUM_BONE_INFLUENCERS 0");
  86336. }
  86337. // Instances
  86338. if (useInstances) {
  86339. defines.push("#define INSTANCES");
  86340. attribs.push("world0");
  86341. attribs.push("world1");
  86342. attribs.push("world2");
  86343. attribs.push("world3");
  86344. }
  86345. // Get correct effect
  86346. var join = defines.join("\n");
  86347. if (this._cachedDefines !== join) {
  86348. this._cachedDefines = join;
  86349. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  86350. }
  86351. return this._effectLayerMapGenerationEffect.isReady();
  86352. };
  86353. /**
  86354. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  86355. */
  86356. EffectLayer.prototype.render = function () {
  86357. var currentEffect = this._mergeEffect;
  86358. // Check
  86359. if (!currentEffect.isReady())
  86360. return;
  86361. for (var i = 0; i < this._postProcesses.length; i++) {
  86362. if (!this._postProcesses[i].isReady()) {
  86363. return;
  86364. }
  86365. }
  86366. var engine = this._scene.getEngine();
  86367. this.onBeforeComposeObservable.notifyObservers(this);
  86368. // Render
  86369. engine.enableEffect(currentEffect);
  86370. engine.setState(false);
  86371. // VBOs
  86372. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  86373. // Cache
  86374. var previousAlphaMode = engine.getAlphaMode();
  86375. // Go Blend.
  86376. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  86377. // Blends the map on the main canvas.
  86378. this._internalRender(currentEffect);
  86379. // Restore Alpha
  86380. engine.setAlphaMode(previousAlphaMode);
  86381. this.onAfterComposeObservable.notifyObservers(this);
  86382. // Handle size changes.
  86383. var size = this._mainTexture.getSize();
  86384. this._setMainTextureSize();
  86385. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  86386. // Recreate RTT and post processes on size change.
  86387. this.onSizeChangedObservable.notifyObservers(this);
  86388. this._disposeTextureAndPostProcesses();
  86389. this._createMainTexture();
  86390. this._createTextureAndPostProcesses();
  86391. }
  86392. };
  86393. /**
  86394. * Determine if a given mesh will be used in the current effect.
  86395. * @param mesh mesh to test
  86396. * @returns true if the mesh will be used
  86397. */
  86398. EffectLayer.prototype.hasMesh = function (mesh) {
  86399. return true;
  86400. };
  86401. /**
  86402. * Returns true if the layer contains information to display, otherwise false.
  86403. * @returns true if the glow layer should be rendered
  86404. */
  86405. EffectLayer.prototype.shouldRender = function () {
  86406. return this.isEnabled && this._shouldRender;
  86407. };
  86408. /**
  86409. * Returns true if the mesh should render, otherwise false.
  86410. * @param mesh The mesh to render
  86411. * @returns true if it should render otherwise false
  86412. */
  86413. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  86414. return true;
  86415. };
  86416. /**
  86417. * Returns true if the mesh should render, otherwise false.
  86418. * @param mesh The mesh to render
  86419. * @returns true if it should render otherwise false
  86420. */
  86421. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  86422. return true;
  86423. };
  86424. /**
  86425. * Renders the submesh passed in parameter to the generation map.
  86426. */
  86427. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  86428. var _this = this;
  86429. if (!this.shouldRender()) {
  86430. return;
  86431. }
  86432. var material = subMesh.getMaterial();
  86433. var mesh = subMesh.getRenderingMesh();
  86434. var scene = this._scene;
  86435. var engine = scene.getEngine();
  86436. if (!material) {
  86437. return;
  86438. }
  86439. // Do not block in blend mode.
  86440. if (material.needAlphaBlendingForMesh(mesh)) {
  86441. return;
  86442. }
  86443. // Culling
  86444. engine.setState(material.backFaceCulling);
  86445. // Managing instances
  86446. var batch = mesh._getInstancesRenderList(subMesh._id);
  86447. if (batch.mustReturn) {
  86448. return;
  86449. }
  86450. // Early Exit per mesh
  86451. if (!this._shouldRenderMesh(mesh)) {
  86452. return;
  86453. }
  86454. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  86455. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  86456. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  86457. engine.enableEffect(this._effectLayerMapGenerationEffect);
  86458. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  86459. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  86460. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  86461. // Alpha test
  86462. if (material && material.needAlphaTesting()) {
  86463. var alphaTexture = material.getAlphaTestTexture();
  86464. if (alphaTexture) {
  86465. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  86466. var textureMatrix = alphaTexture.getTextureMatrix();
  86467. if (textureMatrix) {
  86468. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  86469. }
  86470. }
  86471. }
  86472. // Glow emissive only
  86473. if (this._emissiveTextureAndColor.texture) {
  86474. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  86475. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  86476. }
  86477. // Bones
  86478. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  86479. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  86480. }
  86481. // Draw
  86482. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  86483. }
  86484. else {
  86485. // Need to reset refresh rate of the shadowMap
  86486. this._mainTexture.resetRefreshCounter();
  86487. }
  86488. };
  86489. /**
  86490. * Rebuild the required buffers.
  86491. * @ignore Internal use only.
  86492. */
  86493. EffectLayer.prototype._rebuild = function () {
  86494. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86495. if (vb) {
  86496. vb._rebuild();
  86497. }
  86498. this._generateIndexBuffer();
  86499. };
  86500. /**
  86501. * Dispose only the render target textures and post process.
  86502. */
  86503. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  86504. this._mainTexture.dispose();
  86505. for (var i = 0; i < this._postProcesses.length; i++) {
  86506. if (this._postProcesses[i]) {
  86507. this._postProcesses[i].dispose();
  86508. }
  86509. }
  86510. this._postProcesses = [];
  86511. for (var i = 0; i < this._textures.length; i++) {
  86512. if (this._textures[i]) {
  86513. this._textures[i].dispose();
  86514. }
  86515. }
  86516. this._textures = [];
  86517. };
  86518. /**
  86519. * Dispose the highlight layer and free resources.
  86520. */
  86521. EffectLayer.prototype.dispose = function () {
  86522. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  86523. if (vertexBuffer) {
  86524. vertexBuffer.dispose();
  86525. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  86526. }
  86527. if (this._indexBuffer) {
  86528. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  86529. this._indexBuffer = null;
  86530. }
  86531. // Clean textures and post processes
  86532. this._disposeTextureAndPostProcesses();
  86533. // Remove from scene
  86534. var index = this._scene.effectLayers.indexOf(this, 0);
  86535. if (index > -1) {
  86536. this._scene.effectLayers.splice(index, 1);
  86537. }
  86538. // Callback
  86539. this.onDisposeObservable.notifyObservers(this);
  86540. this.onDisposeObservable.clear();
  86541. this.onBeforeRenderMainTextureObservable.clear();
  86542. this.onBeforeComposeObservable.clear();
  86543. this.onAfterComposeObservable.clear();
  86544. this.onSizeChangedObservable.clear();
  86545. };
  86546. return EffectLayer;
  86547. }());
  86548. BABYLON.EffectLayer = EffectLayer;
  86549. })(BABYLON || (BABYLON = {}));
  86550. //# sourceMappingURL=babylon.effectLayer.js.map
  86551. "use strict";
  86552. var BABYLON;
  86553. (function (BABYLON) {
  86554. /**
  86555. * Special Glow Blur post process only blurring the alpha channel
  86556. * It enforces keeping the most luminous color in the color channel.
  86557. */
  86558. var GlowBlurPostProcess = /** @class */ (function (_super) {
  86559. __extends(GlowBlurPostProcess, _super);
  86560. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  86561. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  86562. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  86563. _this.direction = direction;
  86564. _this.kernel = kernel;
  86565. _this.onApplyObservable.add(function (effect) {
  86566. effect.setFloat2("screenSize", _this.width, _this.height);
  86567. effect.setVector2("direction", _this.direction);
  86568. effect.setFloat("blurWidth", _this.kernel);
  86569. });
  86570. return _this;
  86571. }
  86572. return GlowBlurPostProcess;
  86573. }(BABYLON.PostProcess));
  86574. /**
  86575. * The highlight layer Helps adding a glow effect around a mesh.
  86576. *
  86577. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  86578. * glowy meshes to your scene.
  86579. *
  86580. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  86581. */
  86582. var HighlightLayer = /** @class */ (function (_super) {
  86583. __extends(HighlightLayer, _super);
  86584. /**
  86585. * Instantiates a new highlight Layer and references it to the scene..
  86586. * @param name The name of the layer
  86587. * @param scene The scene to use the layer in
  86588. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  86589. */
  86590. function HighlightLayer(name, scene, options) {
  86591. var _this = _super.call(this, name, scene) || this;
  86592. _this.name = name;
  86593. /**
  86594. * Specifies whether or not the inner glow is ACTIVE in the layer.
  86595. */
  86596. _this.innerGlow = true;
  86597. /**
  86598. * Specifies whether or not the outer glow is ACTIVE in the layer.
  86599. */
  86600. _this.outerGlow = true;
  86601. /**
  86602. * An event triggered when the highlight layer is being blurred.
  86603. */
  86604. _this.onBeforeBlurObservable = new BABYLON.Observable();
  86605. /**
  86606. * An event triggered when the highlight layer has been blurred.
  86607. */
  86608. _this.onAfterBlurObservable = new BABYLON.Observable();
  86609. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  86610. _this._meshes = {};
  86611. _this._excludedMeshes = {};
  86612. _this.neutralColor = HighlightLayer.NeutralColor;
  86613. // Warn on stencil
  86614. if (!_this._engine.isStencilEnable) {
  86615. 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 }");
  86616. }
  86617. // Adapt options
  86618. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  86619. // Initialize the layer
  86620. _this._init({
  86621. alphaBlendingMode: _this._options.alphaBlendingMode,
  86622. camera: _this._options.camera,
  86623. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  86624. mainTextureRatio: _this._options.mainTextureRatio
  86625. });
  86626. // Do not render as long as no meshes have been added
  86627. _this._shouldRender = false;
  86628. return _this;
  86629. }
  86630. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  86631. /**
  86632. * Gets the horizontal size of the blur.
  86633. */
  86634. get: function () {
  86635. return this._horizontalBlurPostprocess.kernel;
  86636. },
  86637. /**
  86638. * Specifies the horizontal size of the blur.
  86639. */
  86640. set: function (value) {
  86641. this._horizontalBlurPostprocess.kernel = value;
  86642. },
  86643. enumerable: true,
  86644. configurable: true
  86645. });
  86646. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  86647. /**
  86648. * Gets the vertical size of the blur.
  86649. */
  86650. get: function () {
  86651. return this._verticalBlurPostprocess.kernel;
  86652. },
  86653. /**
  86654. * Specifies the vertical size of the blur.
  86655. */
  86656. set: function (value) {
  86657. this._verticalBlurPostprocess.kernel = value;
  86658. },
  86659. enumerable: true,
  86660. configurable: true
  86661. });
  86662. /**
  86663. * Get the effect name of the layer.
  86664. * @return The effect name
  86665. */
  86666. HighlightLayer.prototype.getEffectName = function () {
  86667. return HighlightLayer.EffectName;
  86668. };
  86669. /**
  86670. * Create the merge effect. This is the shader use to blit the information back
  86671. * to the main canvas at the end of the scene rendering.
  86672. */
  86673. HighlightLayer.prototype._createMergeEffect = function () {
  86674. // Effect
  86675. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  86676. };
  86677. /**
  86678. * Creates the render target textures and post processes used in the highlight layer.
  86679. */
  86680. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  86681. var _this = this;
  86682. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  86683. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  86684. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  86685. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  86686. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  86687. width: blurTextureWidth,
  86688. height: blurTextureHeight
  86689. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86690. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86691. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  86692. this._blurTexture.anisotropicFilteringLevel = 16;
  86693. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  86694. this._blurTexture.renderParticles = false;
  86695. this._blurTexture.ignoreCameraViewport = true;
  86696. this._textures = [this._blurTexture];
  86697. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  86698. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  86699. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  86700. effect.setTexture("textureSampler", _this._mainTexture);
  86701. });
  86702. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  86703. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  86704. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  86705. });
  86706. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  86707. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  86708. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  86709. });
  86710. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  86711. }
  86712. else {
  86713. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  86714. width: blurTextureWidth,
  86715. height: blurTextureHeight
  86716. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86717. this._horizontalBlurPostprocess.width = blurTextureWidth;
  86718. this._horizontalBlurPostprocess.height = blurTextureHeight;
  86719. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  86720. effect.setTexture("textureSampler", _this._mainTexture);
  86721. });
  86722. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  86723. width: blurTextureWidth,
  86724. height: blurTextureHeight
  86725. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  86726. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  86727. }
  86728. this._mainTexture.onAfterUnbindObservable.add(function () {
  86729. _this.onBeforeBlurObservable.notifyObservers(_this);
  86730. var internalTexture = _this._blurTexture.getInternalTexture();
  86731. if (internalTexture) {
  86732. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  86733. }
  86734. _this.onAfterBlurObservable.notifyObservers(_this);
  86735. });
  86736. // Prevent autoClear.
  86737. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  86738. };
  86739. /**
  86740. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  86741. */
  86742. HighlightLayer.prototype.needStencil = function () {
  86743. return true;
  86744. };
  86745. /**
  86746. * Checks for the readiness of the element composing the layer.
  86747. * @param subMesh the mesh to check for
  86748. * @param useInstances specify wether or not to use instances to render the mesh
  86749. * @param emissiveTexture the associated emissive texture used to generate the glow
  86750. * @return true if ready otherwise, false
  86751. */
  86752. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  86753. var material = subMesh.getMaterial();
  86754. var mesh = subMesh.getRenderingMesh();
  86755. if (!material || !mesh || !this._meshes) {
  86756. return false;
  86757. }
  86758. var emissiveTexture = null;
  86759. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  86760. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  86761. emissiveTexture = material.emissiveTexture;
  86762. }
  86763. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  86764. };
  86765. /**
  86766. * Implementation specific of rendering the generating effect on the main canvas.
  86767. * @param effect The effect used to render through
  86768. */
  86769. HighlightLayer.prototype._internalRender = function (effect) {
  86770. // Texture
  86771. effect.setTexture("textureSampler", this._blurTexture);
  86772. // Cache
  86773. var engine = this._engine;
  86774. var previousStencilBuffer = engine.getStencilBuffer();
  86775. var previousStencilFunction = engine.getStencilFunction();
  86776. var previousStencilMask = engine.getStencilMask();
  86777. var previousStencilOperationPass = engine.getStencilOperationPass();
  86778. var previousStencilOperationFail = engine.getStencilOperationFail();
  86779. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  86780. var previousStencilReference = engine.getStencilFunctionReference();
  86781. // Stencil operations
  86782. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  86783. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  86784. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  86785. // Draw order
  86786. engine.setStencilMask(0x00);
  86787. engine.setStencilBuffer(true);
  86788. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  86789. // 2 passes inner outer
  86790. if (this.outerGlow) {
  86791. effect.setFloat("offset", 0);
  86792. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  86793. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86794. }
  86795. if (this.innerGlow) {
  86796. effect.setFloat("offset", 1);
  86797. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  86798. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  86799. }
  86800. // Restore Cache
  86801. engine.setStencilFunction(previousStencilFunction);
  86802. engine.setStencilMask(previousStencilMask);
  86803. engine.setStencilBuffer(previousStencilBuffer);
  86804. engine.setStencilOperationPass(previousStencilOperationPass);
  86805. engine.setStencilOperationFail(previousStencilOperationFail);
  86806. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  86807. engine.setStencilFunctionReference(previousStencilReference);
  86808. };
  86809. /**
  86810. * Returns true if the layer contains information to display, otherwise false.
  86811. */
  86812. HighlightLayer.prototype.shouldRender = function () {
  86813. if (_super.prototype.shouldRender.call(this)) {
  86814. return this._meshes ? true : false;
  86815. }
  86816. return false;
  86817. };
  86818. /**
  86819. * Returns true if the mesh should render, otherwise false.
  86820. * @param mesh The mesh to render
  86821. * @returns true if it should render otherwise false
  86822. */
  86823. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  86824. // Excluded Mesh
  86825. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  86826. return false;
  86827. }
  86828. ;
  86829. return true;
  86830. };
  86831. /**
  86832. * Sets the required values for both the emissive texture and and the main color.
  86833. */
  86834. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  86835. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  86836. if (highlightLayerMesh) {
  86837. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  86838. }
  86839. else {
  86840. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  86841. }
  86842. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  86843. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  86844. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  86845. }
  86846. else {
  86847. this._emissiveTextureAndColor.texture = null;
  86848. }
  86849. };
  86850. /**
  86851. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  86852. * @param mesh The mesh to exclude from the highlight layer
  86853. */
  86854. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  86855. if (!this._excludedMeshes) {
  86856. return;
  86857. }
  86858. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  86859. if (!meshExcluded) {
  86860. this._excludedMeshes[mesh.uniqueId] = {
  86861. mesh: mesh,
  86862. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  86863. mesh.getEngine().setStencilBuffer(false);
  86864. }),
  86865. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  86866. mesh.getEngine().setStencilBuffer(true);
  86867. }),
  86868. };
  86869. }
  86870. };
  86871. /**
  86872. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  86873. * @param mesh The mesh to highlight
  86874. */
  86875. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  86876. if (!this._excludedMeshes) {
  86877. return;
  86878. }
  86879. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  86880. if (meshExcluded) {
  86881. if (meshExcluded.beforeRender) {
  86882. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  86883. }
  86884. if (meshExcluded.afterRender) {
  86885. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  86886. }
  86887. }
  86888. this._excludedMeshes[mesh.uniqueId] = null;
  86889. };
  86890. /**
  86891. * Determine if a given mesh will be highlighted by the current HighlightLayer
  86892. * @param mesh mesh to test
  86893. * @returns true if the mesh will be highlighted by the current HighlightLayer
  86894. */
  86895. HighlightLayer.prototype.hasMesh = function (mesh) {
  86896. if (!this._meshes) {
  86897. return false;
  86898. }
  86899. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  86900. };
  86901. /**
  86902. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  86903. * @param mesh The mesh to highlight
  86904. * @param color The color of the highlight
  86905. * @param glowEmissiveOnly Extract the glow from the emissive texture
  86906. */
  86907. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  86908. var _this = this;
  86909. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  86910. if (!this._meshes) {
  86911. return;
  86912. }
  86913. var meshHighlight = this._meshes[mesh.uniqueId];
  86914. if (meshHighlight) {
  86915. meshHighlight.color = color;
  86916. }
  86917. else {
  86918. this._meshes[mesh.uniqueId] = {
  86919. mesh: mesh,
  86920. color: color,
  86921. // Lambda required for capture due to Observable this context
  86922. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  86923. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  86924. _this._defaultStencilReference(mesh);
  86925. }
  86926. else {
  86927. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  86928. }
  86929. }),
  86930. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  86931. glowEmissiveOnly: glowEmissiveOnly
  86932. };
  86933. }
  86934. this._shouldRender = true;
  86935. };
  86936. /**
  86937. * Remove a mesh from the highlight layer in order to make it stop glowing.
  86938. * @param mesh The mesh to highlight
  86939. */
  86940. HighlightLayer.prototype.removeMesh = function (mesh) {
  86941. if (!this._meshes) {
  86942. return;
  86943. }
  86944. var meshHighlight = this._meshes[mesh.uniqueId];
  86945. if (meshHighlight) {
  86946. if (meshHighlight.observerHighlight) {
  86947. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  86948. }
  86949. if (meshHighlight.observerDefault) {
  86950. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  86951. }
  86952. delete this._meshes[mesh.uniqueId];
  86953. }
  86954. this._shouldRender = false;
  86955. for (var meshHighlightToCheck in this._meshes) {
  86956. if (this._meshes[meshHighlightToCheck]) {
  86957. this._shouldRender = true;
  86958. break;
  86959. }
  86960. }
  86961. };
  86962. /**
  86963. * Force the stencil to the normal expected value for none glowing parts
  86964. */
  86965. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  86966. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  86967. };
  86968. /**
  86969. * Free any resources and references associated to a mesh.
  86970. * Internal use
  86971. * @param mesh The mesh to free.
  86972. */
  86973. HighlightLayer.prototype._disposeMesh = function (mesh) {
  86974. this.removeMesh(mesh);
  86975. this.removeExcludedMesh(mesh);
  86976. };
  86977. /**
  86978. * Dispose the highlight layer and free resources.
  86979. */
  86980. HighlightLayer.prototype.dispose = function () {
  86981. if (this._meshes) {
  86982. // Clean mesh references
  86983. for (var id in this._meshes) {
  86984. var meshHighlight = this._meshes[id];
  86985. if (meshHighlight && meshHighlight.mesh) {
  86986. if (meshHighlight.observerHighlight) {
  86987. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  86988. }
  86989. if (meshHighlight.observerDefault) {
  86990. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  86991. }
  86992. }
  86993. }
  86994. this._meshes = null;
  86995. }
  86996. if (this._excludedMeshes) {
  86997. for (var id in this._excludedMeshes) {
  86998. var meshHighlight = this._excludedMeshes[id];
  86999. if (meshHighlight) {
  87000. if (meshHighlight.beforeRender) {
  87001. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  87002. }
  87003. if (meshHighlight.afterRender) {
  87004. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  87005. }
  87006. }
  87007. }
  87008. this._excludedMeshes = null;
  87009. }
  87010. _super.prototype.dispose.call(this);
  87011. };
  87012. /**
  87013. * Effect Name of the highlight layer.
  87014. */
  87015. HighlightLayer.EffectName = "HighlightLayer";
  87016. /**
  87017. * The neutral color used during the preparation of the glow effect.
  87018. * This is black by default as the blend operation is a blend operation.
  87019. */
  87020. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  87021. /**
  87022. * Stencil value used for glowing meshes.
  87023. */
  87024. HighlightLayer.GlowingMeshStencilReference = 0x02;
  87025. /**
  87026. * Stencil value used for the other meshes in the scene.
  87027. */
  87028. HighlightLayer.NormalMeshStencilReference = 0x01;
  87029. return HighlightLayer;
  87030. }(BABYLON.EffectLayer));
  87031. BABYLON.HighlightLayer = HighlightLayer;
  87032. })(BABYLON || (BABYLON = {}));
  87033. //# sourceMappingURL=babylon.highlightLayer.js.map
  87034. "use strict";
  87035. var BABYLON;
  87036. (function (BABYLON) {
  87037. /**
  87038. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  87039. *
  87040. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  87041. * glowy meshes to your scene.
  87042. *
  87043. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  87044. */
  87045. var GlowLayer = /** @class */ (function (_super) {
  87046. __extends(GlowLayer, _super);
  87047. /**
  87048. * Instantiates a new glow Layer and references it to the scene.
  87049. * @param name The name of the layer
  87050. * @param scene The scene to use the layer in
  87051. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  87052. */
  87053. function GlowLayer(name, scene, options) {
  87054. var _this = _super.call(this, name, scene) || this;
  87055. _this.name = name;
  87056. _this._intensity = 1.0;
  87057. _this._includedOnlyMeshes = [];
  87058. _this._excludedMeshes = [];
  87059. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  87060. // Adapt options
  87061. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  87062. // Initialize the layer
  87063. _this._init({
  87064. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  87065. camera: _this._options.camera,
  87066. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  87067. mainTextureRatio: _this._options.mainTextureRatio
  87068. });
  87069. return _this;
  87070. }
  87071. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  87072. /**
  87073. * Gets the kernel size of the blur.
  87074. */
  87075. get: function () {
  87076. return this._horizontalBlurPostprocess1.kernel;
  87077. },
  87078. /**
  87079. * Sets the kernel size of the blur.
  87080. */
  87081. set: function (value) {
  87082. this._horizontalBlurPostprocess1.kernel = value;
  87083. this._verticalBlurPostprocess1.kernel = value;
  87084. this._horizontalBlurPostprocess2.kernel = value;
  87085. this._verticalBlurPostprocess2.kernel = value;
  87086. },
  87087. enumerable: true,
  87088. configurable: true
  87089. });
  87090. Object.defineProperty(GlowLayer.prototype, "intensity", {
  87091. /**
  87092. * Gets the glow intensity.
  87093. */
  87094. get: function () {
  87095. return this._intensity;
  87096. },
  87097. /**
  87098. * Sets the glow intensity.
  87099. */
  87100. set: function (value) {
  87101. this._intensity = value;
  87102. },
  87103. enumerable: true,
  87104. configurable: true
  87105. });
  87106. /**
  87107. * Get the effect name of the layer.
  87108. * @return The effect name
  87109. */
  87110. GlowLayer.prototype.getEffectName = function () {
  87111. return GlowLayer.EffectName;
  87112. };
  87113. /**
  87114. * Create the merge effect. This is the shader use to blit the information back
  87115. * to the main canvas at the end of the scene rendering.
  87116. */
  87117. GlowLayer.prototype._createMergeEffect = function () {
  87118. // Effect
  87119. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  87120. };
  87121. /**
  87122. * Creates the render target textures and post processes used in the glow layer.
  87123. */
  87124. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  87125. var _this = this;
  87126. var blurTextureWidth = this._mainTextureDesiredSize.width;
  87127. var blurTextureHeight = this._mainTextureDesiredSize.height;
  87128. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  87129. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  87130. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  87131. width: blurTextureWidth,
  87132. height: blurTextureHeight
  87133. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87134. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87135. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87136. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  87137. this._blurTexture1.renderParticles = false;
  87138. this._blurTexture1.ignoreCameraViewport = true;
  87139. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  87140. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  87141. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  87142. width: blurTextureWidth2,
  87143. height: blurTextureHeight2
  87144. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87145. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87146. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87147. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  87148. this._blurTexture2.renderParticles = false;
  87149. this._blurTexture2.ignoreCameraViewport = true;
  87150. this._textures = [this._blurTexture1, this._blurTexture2];
  87151. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  87152. width: blurTextureWidth,
  87153. height: blurTextureHeight
  87154. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87155. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  87156. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  87157. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  87158. effect.setTexture("textureSampler", _this._mainTexture);
  87159. });
  87160. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  87161. width: blurTextureWidth,
  87162. height: blurTextureHeight
  87163. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87164. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  87165. width: blurTextureWidth2,
  87166. height: blurTextureHeight2
  87167. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87168. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  87169. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  87170. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  87171. effect.setTexture("textureSampler", _this._blurTexture1);
  87172. });
  87173. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  87174. width: blurTextureWidth2,
  87175. height: blurTextureHeight2
  87176. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  87177. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  87178. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  87179. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  87180. this._mainTexture.samples = this._options.mainTextureSamples;
  87181. this._mainTexture.onAfterUnbindObservable.add(function () {
  87182. var internalTexture = _this._blurTexture1.getInternalTexture();
  87183. if (internalTexture) {
  87184. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  87185. internalTexture = _this._blurTexture2.getInternalTexture();
  87186. if (internalTexture) {
  87187. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  87188. }
  87189. }
  87190. });
  87191. // Prevent autoClear.
  87192. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  87193. };
  87194. /**
  87195. * Checks for the readiness of the element composing the layer.
  87196. * @param subMesh the mesh to check for
  87197. * @param useInstances specify wether or not to use instances to render the mesh
  87198. * @param emissiveTexture the associated emissive texture used to generate the glow
  87199. * @return true if ready otherwise, false
  87200. */
  87201. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  87202. var material = subMesh.getMaterial();
  87203. var mesh = subMesh.getRenderingMesh();
  87204. if (!material || !mesh) {
  87205. return false;
  87206. }
  87207. var emissiveTexture = material.emissiveTexture;
  87208. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  87209. };
  87210. /**
  87211. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  87212. */
  87213. GlowLayer.prototype.needStencil = function () {
  87214. return false;
  87215. };
  87216. /**
  87217. * Implementation specific of rendering the generating effect on the main canvas.
  87218. * @param effect The effect used to render through
  87219. */
  87220. GlowLayer.prototype._internalRender = function (effect) {
  87221. // Texture
  87222. effect.setTexture("textureSampler", this._blurTexture1);
  87223. effect.setTexture("textureSampler2", this._blurTexture2);
  87224. effect.setFloat("offset", this._intensity);
  87225. // Cache
  87226. var engine = this._engine;
  87227. var previousStencilBuffer = engine.getStencilBuffer();
  87228. // Draw order
  87229. engine.setStencilBuffer(false);
  87230. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  87231. // Draw order
  87232. engine.setStencilBuffer(previousStencilBuffer);
  87233. };
  87234. /**
  87235. * Sets the required values for both the emissive texture and and the main color.
  87236. */
  87237. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  87238. var textureLevel = 1.0;
  87239. if (this.customEmissiveTextureSelector) {
  87240. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  87241. }
  87242. else {
  87243. if (material) {
  87244. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  87245. if (this._emissiveTextureAndColor.texture) {
  87246. textureLevel = this._emissiveTextureAndColor.texture.level;
  87247. }
  87248. }
  87249. else {
  87250. this._emissiveTextureAndColor.texture = null;
  87251. }
  87252. }
  87253. if (this.customEmissiveColorSelector) {
  87254. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  87255. }
  87256. else {
  87257. if (material.emissiveColor) {
  87258. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  87259. }
  87260. else {
  87261. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  87262. }
  87263. }
  87264. };
  87265. /**
  87266. * Returns true if the mesh should render, otherwise false.
  87267. * @param mesh The mesh to render
  87268. * @returns true if it should render otherwise false
  87269. */
  87270. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  87271. return this.hasMesh(mesh);
  87272. };
  87273. /**
  87274. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  87275. * @param mesh The mesh to exclude from the glow layer
  87276. */
  87277. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  87278. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  87279. this._excludedMeshes.push(mesh.uniqueId);
  87280. }
  87281. };
  87282. /**
  87283. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  87284. * @param mesh The mesh to remove
  87285. */
  87286. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  87287. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  87288. if (index !== -1) {
  87289. this._excludedMeshes.splice(index, 1);
  87290. }
  87291. };
  87292. /**
  87293. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  87294. * @param mesh The mesh to include in the glow layer
  87295. */
  87296. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  87297. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  87298. this._includedOnlyMeshes.push(mesh.uniqueId);
  87299. }
  87300. };
  87301. /**
  87302. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  87303. * @param mesh The mesh to remove
  87304. */
  87305. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  87306. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  87307. if (index !== -1) {
  87308. this._includedOnlyMeshes.splice(index, 1);
  87309. }
  87310. };
  87311. /**
  87312. * Determine if a given mesh will be used in the glow layer
  87313. * @param mesh The mesh to test
  87314. * @returns true if the mesh will be highlighted by the current glow layer
  87315. */
  87316. GlowLayer.prototype.hasMesh = function (mesh) {
  87317. // Included Mesh
  87318. if (this._includedOnlyMeshes.length) {
  87319. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  87320. }
  87321. ;
  87322. // Excluded Mesh
  87323. if (this._excludedMeshes.length) {
  87324. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  87325. }
  87326. ;
  87327. return true;
  87328. };
  87329. /**
  87330. * Free any resources and references associated to a mesh.
  87331. * Internal use
  87332. * @param mesh The mesh to free.
  87333. */
  87334. GlowLayer.prototype._disposeMesh = function (mesh) {
  87335. this.removeIncludedOnlyMesh(mesh);
  87336. this.removeExcludedMesh(mesh);
  87337. };
  87338. /**
  87339. * Effect Name of the layer.
  87340. */
  87341. GlowLayer.EffectName = "GlowLayer";
  87342. /**
  87343. * The default blur kernel size used for the glow.
  87344. */
  87345. GlowLayer.DefaultBlurKernelSize = 32;
  87346. /**
  87347. * The default texture size ratio used for the glow.
  87348. */
  87349. GlowLayer.DefaultTextureRatio = 0.5;
  87350. return GlowLayer;
  87351. }(BABYLON.EffectLayer));
  87352. BABYLON.GlowLayer = GlowLayer;
  87353. })(BABYLON || (BABYLON = {}));
  87354. //# sourceMappingURL=babylon.glowLayer.js.map
  87355. "use strict";
  87356. var BABYLON;
  87357. (function (BABYLON) {
  87358. /**
  87359. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  87360. */
  87361. var AssetTaskState;
  87362. (function (AssetTaskState) {
  87363. /**
  87364. * Initialization
  87365. */
  87366. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  87367. /**
  87368. * Running
  87369. */
  87370. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  87371. /**
  87372. * Done
  87373. */
  87374. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  87375. /**
  87376. * Error
  87377. */
  87378. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  87379. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  87380. /**
  87381. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  87382. */
  87383. var AbstractAssetTask = /** @class */ (function () {
  87384. /**
  87385. * Creates a new {BABYLON.AssetsManager}
  87386. * @param name defines the name of the task
  87387. */
  87388. function AbstractAssetTask(
  87389. /**
  87390. * Task name
  87391. */ name) {
  87392. this.name = name;
  87393. this._isCompleted = false;
  87394. this._taskState = AssetTaskState.INIT;
  87395. }
  87396. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  87397. /**
  87398. * Get if the task is completed
  87399. */
  87400. get: function () {
  87401. return this._isCompleted;
  87402. },
  87403. enumerable: true,
  87404. configurable: true
  87405. });
  87406. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  87407. /**
  87408. * Gets the current state of the task
  87409. */
  87410. get: function () {
  87411. return this._taskState;
  87412. },
  87413. enumerable: true,
  87414. configurable: true
  87415. });
  87416. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  87417. /**
  87418. * Gets the current error object (if task is in error)
  87419. */
  87420. get: function () {
  87421. return this._errorObject;
  87422. },
  87423. enumerable: true,
  87424. configurable: true
  87425. });
  87426. /**
  87427. * Internal only
  87428. * @ignore
  87429. */
  87430. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  87431. if (this._errorObject) {
  87432. return;
  87433. }
  87434. this._errorObject = {
  87435. message: message,
  87436. exception: exception
  87437. };
  87438. };
  87439. /**
  87440. * Execute the current task
  87441. * @param scene defines the scene where you want your assets to be loaded
  87442. * @param onSuccess is a callback called when the task is successfully executed
  87443. * @param onError is a callback called if an error occurs
  87444. */
  87445. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  87446. var _this = this;
  87447. this._taskState = AssetTaskState.RUNNING;
  87448. this.runTask(scene, function () {
  87449. _this.onDoneCallback(onSuccess, onError);
  87450. }, function (msg, exception) {
  87451. _this.onErrorCallback(onError, msg, exception);
  87452. });
  87453. };
  87454. /**
  87455. * Execute the current task
  87456. * @param scene defines the scene where you want your assets to be loaded
  87457. * @param onSuccess is a callback called when the task is successfully executed
  87458. * @param onError is a callback called if an error occurs
  87459. */
  87460. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87461. throw new Error("runTask is not implemented");
  87462. };
  87463. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  87464. this._taskState = AssetTaskState.ERROR;
  87465. this._errorObject = {
  87466. message: message,
  87467. exception: exception
  87468. };
  87469. if (this.onError) {
  87470. this.onError(this, message, exception);
  87471. }
  87472. onError();
  87473. };
  87474. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  87475. try {
  87476. this._taskState = AssetTaskState.DONE;
  87477. this._isCompleted = true;
  87478. if (this.onSuccess) {
  87479. this.onSuccess(this);
  87480. }
  87481. onSuccess();
  87482. }
  87483. catch (e) {
  87484. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  87485. }
  87486. };
  87487. return AbstractAssetTask;
  87488. }());
  87489. BABYLON.AbstractAssetTask = AbstractAssetTask;
  87490. /**
  87491. * Class used to share progress information about assets loading
  87492. */
  87493. var AssetsProgressEvent = /** @class */ (function () {
  87494. /**
  87495. * Creates a {BABYLON.AssetsProgressEvent}
  87496. * @param remainingCount defines the number of remaining tasks to process
  87497. * @param totalCount defines the total number of tasks
  87498. * @param task defines the task that was just processed
  87499. */
  87500. function AssetsProgressEvent(remainingCount, totalCount, task) {
  87501. this.remainingCount = remainingCount;
  87502. this.totalCount = totalCount;
  87503. this.task = task;
  87504. }
  87505. return AssetsProgressEvent;
  87506. }());
  87507. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  87508. /**
  87509. * Define a task used by {BABYLON.AssetsManager} to load meshes
  87510. */
  87511. var MeshAssetTask = /** @class */ (function (_super) {
  87512. __extends(MeshAssetTask, _super);
  87513. /**
  87514. * Creates a new {BABYLON.MeshAssetTask}
  87515. * @param name defines the name of the task
  87516. * @param meshesNames defines the list of mesh's names you want to load
  87517. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  87518. * @param sceneFilename defines the filename of the scene to load from
  87519. */
  87520. function MeshAssetTask(
  87521. /**
  87522. * Defines the name of the task
  87523. */
  87524. name,
  87525. /**
  87526. * Defines the list of mesh's names you want to load
  87527. */
  87528. meshesNames,
  87529. /**
  87530. * Defines the root url to use as a base to load your meshes and associated resources
  87531. */
  87532. rootUrl,
  87533. /**
  87534. * Defines the filename of the scene to load from
  87535. */
  87536. sceneFilename) {
  87537. var _this = _super.call(this, name) || this;
  87538. _this.name = name;
  87539. _this.meshesNames = meshesNames;
  87540. _this.rootUrl = rootUrl;
  87541. _this.sceneFilename = sceneFilename;
  87542. return _this;
  87543. }
  87544. /**
  87545. * Execute the current task
  87546. * @param scene defines the scene where you want your assets to be loaded
  87547. * @param onSuccess is a callback called when the task is successfully executed
  87548. * @param onError is a callback called if an error occurs
  87549. */
  87550. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87551. var _this = this;
  87552. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  87553. _this.loadedMeshes = meshes;
  87554. _this.loadedParticleSystems = particleSystems;
  87555. _this.loadedSkeletons = skeletons;
  87556. onSuccess();
  87557. }, null, function (scene, message, exception) {
  87558. onError(message, exception);
  87559. });
  87560. };
  87561. return MeshAssetTask;
  87562. }(AbstractAssetTask));
  87563. BABYLON.MeshAssetTask = MeshAssetTask;
  87564. /**
  87565. * Define a task used by {BABYLON.AssetsManager} to load text content
  87566. */
  87567. var TextFileAssetTask = /** @class */ (function (_super) {
  87568. __extends(TextFileAssetTask, _super);
  87569. /**
  87570. * Creates a new TextFileAssetTask object
  87571. * @param name defines the name of the task
  87572. * @param url defines the location of the file to load
  87573. */
  87574. function TextFileAssetTask(
  87575. /**
  87576. * Defines the name of the task
  87577. */
  87578. name,
  87579. /**
  87580. * Defines the location of the file to load
  87581. */
  87582. url) {
  87583. var _this = _super.call(this, name) || this;
  87584. _this.name = name;
  87585. _this.url = url;
  87586. return _this;
  87587. }
  87588. /**
  87589. * Execute the current task
  87590. * @param scene defines the scene where you want your assets to be loaded
  87591. * @param onSuccess is a callback called when the task is successfully executed
  87592. * @param onError is a callback called if an error occurs
  87593. */
  87594. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87595. var _this = this;
  87596. scene._loadFile(this.url, function (data) {
  87597. _this.text = data;
  87598. onSuccess();
  87599. }, undefined, false, false, function (request, exception) {
  87600. if (request) {
  87601. onError(request.status + " " + request.statusText, exception);
  87602. }
  87603. });
  87604. };
  87605. return TextFileAssetTask;
  87606. }(AbstractAssetTask));
  87607. BABYLON.TextFileAssetTask = TextFileAssetTask;
  87608. /**
  87609. * Define a task used by {BABYLON.AssetsManager} to load binary data
  87610. */
  87611. var BinaryFileAssetTask = /** @class */ (function (_super) {
  87612. __extends(BinaryFileAssetTask, _super);
  87613. /**
  87614. * Creates a new BinaryFileAssetTask object
  87615. * @param name defines the name of the new task
  87616. * @param url defines the location of the file to load
  87617. */
  87618. function BinaryFileAssetTask(
  87619. /**
  87620. * Defines the name of the task
  87621. */
  87622. name,
  87623. /**
  87624. * Defines the location of the file to load
  87625. */
  87626. url) {
  87627. var _this = _super.call(this, name) || this;
  87628. _this.name = name;
  87629. _this.url = url;
  87630. return _this;
  87631. }
  87632. /**
  87633. * Execute the current task
  87634. * @param scene defines the scene where you want your assets to be loaded
  87635. * @param onSuccess is a callback called when the task is successfully executed
  87636. * @param onError is a callback called if an error occurs
  87637. */
  87638. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87639. var _this = this;
  87640. scene._loadFile(this.url, function (data) {
  87641. _this.data = data;
  87642. onSuccess();
  87643. }, undefined, true, true, function (request, exception) {
  87644. if (request) {
  87645. onError(request.status + " " + request.statusText, exception);
  87646. }
  87647. });
  87648. };
  87649. return BinaryFileAssetTask;
  87650. }(AbstractAssetTask));
  87651. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  87652. /**
  87653. * Define a task used by {BABYLON.AssetsManager} to load images
  87654. */
  87655. var ImageAssetTask = /** @class */ (function (_super) {
  87656. __extends(ImageAssetTask, _super);
  87657. /**
  87658. * Creates a new ImageAssetTask
  87659. * @param name defines the name of the task
  87660. * @param url defines the location of the image to load
  87661. */
  87662. function ImageAssetTask(
  87663. /**
  87664. * Defines the name of the task
  87665. */
  87666. name,
  87667. /**
  87668. * Defines the location of the image to load
  87669. */
  87670. url) {
  87671. var _this = _super.call(this, name) || this;
  87672. _this.name = name;
  87673. _this.url = url;
  87674. return _this;
  87675. }
  87676. /**
  87677. * Execute the current task
  87678. * @param scene defines the scene where you want your assets to be loaded
  87679. * @param onSuccess is a callback called when the task is successfully executed
  87680. * @param onError is a callback called if an error occurs
  87681. */
  87682. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87683. var _this = this;
  87684. var img = new Image();
  87685. BABYLON.Tools.SetCorsBehavior(this.url, img);
  87686. img.onload = function () {
  87687. _this.image = img;
  87688. onSuccess();
  87689. };
  87690. img.onerror = function (err) {
  87691. onError("Error loading image", err);
  87692. };
  87693. img.src = this.url;
  87694. };
  87695. return ImageAssetTask;
  87696. }(AbstractAssetTask));
  87697. BABYLON.ImageAssetTask = ImageAssetTask;
  87698. /**
  87699. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  87700. */
  87701. var TextureAssetTask = /** @class */ (function (_super) {
  87702. __extends(TextureAssetTask, _super);
  87703. /**
  87704. * Creates a new TextureAssetTask object
  87705. * @param name defines the name of the task
  87706. * @param url defines the location of the file to load
  87707. * @param noMipmap defines if mipmap should not be generated (default is false)
  87708. * @param invertY defines if texture must be inverted on Y axis (default is false)
  87709. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  87710. */
  87711. function TextureAssetTask(
  87712. /**
  87713. * Defines the name of the task
  87714. */
  87715. name,
  87716. /**
  87717. * Defines the location of the file to load
  87718. */
  87719. url,
  87720. /**
  87721. * Defines if mipmap should not be generated (default is false)
  87722. */
  87723. noMipmap,
  87724. /**
  87725. * Defines if texture must be inverted on Y axis (default is false)
  87726. */
  87727. invertY,
  87728. /**
  87729. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  87730. */
  87731. samplingMode) {
  87732. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  87733. var _this = _super.call(this, name) || this;
  87734. _this.name = name;
  87735. _this.url = url;
  87736. _this.noMipmap = noMipmap;
  87737. _this.invertY = invertY;
  87738. _this.samplingMode = samplingMode;
  87739. return _this;
  87740. }
  87741. /**
  87742. * Execute the current task
  87743. * @param scene defines the scene where you want your assets to be loaded
  87744. * @param onSuccess is a callback called when the task is successfully executed
  87745. * @param onError is a callback called if an error occurs
  87746. */
  87747. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87748. var onload = function () {
  87749. onSuccess();
  87750. };
  87751. var onerror = function (message, exception) {
  87752. onError(message, exception);
  87753. };
  87754. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  87755. };
  87756. return TextureAssetTask;
  87757. }(AbstractAssetTask));
  87758. BABYLON.TextureAssetTask = TextureAssetTask;
  87759. /**
  87760. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  87761. */
  87762. var CubeTextureAssetTask = /** @class */ (function (_super) {
  87763. __extends(CubeTextureAssetTask, _super);
  87764. /**
  87765. * Creates a new CubeTextureAssetTask
  87766. * @param name defines the name of the task
  87767. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  87768. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  87769. * @param noMipmap defines if mipmaps should not be generated (default is false)
  87770. * @param files defines the explicit list of files (undefined by default)
  87771. */
  87772. function CubeTextureAssetTask(
  87773. /**
  87774. * Defines the name of the task
  87775. */
  87776. name,
  87777. /**
  87778. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  87779. */
  87780. url,
  87781. /**
  87782. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  87783. */
  87784. extensions,
  87785. /**
  87786. * Defines if mipmaps should not be generated (default is false)
  87787. */
  87788. noMipmap,
  87789. /**
  87790. * Defines the explicit list of files (undefined by default)
  87791. */
  87792. files) {
  87793. var _this = _super.call(this, name) || this;
  87794. _this.name = name;
  87795. _this.url = url;
  87796. _this.extensions = extensions;
  87797. _this.noMipmap = noMipmap;
  87798. _this.files = files;
  87799. return _this;
  87800. }
  87801. /**
  87802. * Execute the current task
  87803. * @param scene defines the scene where you want your assets to be loaded
  87804. * @param onSuccess is a callback called when the task is successfully executed
  87805. * @param onError is a callback called if an error occurs
  87806. */
  87807. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  87808. var onload = function () {
  87809. onSuccess();
  87810. };
  87811. var onerror = function (message, exception) {
  87812. onError(message, exception);
  87813. };
  87814. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  87815. };
  87816. return CubeTextureAssetTask;
  87817. }(AbstractAssetTask));
  87818. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  87819. /**
  87820. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  87821. */
  87822. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  87823. __extends(HDRCubeTextureAssetTask, _super);
  87824. /**
  87825. * Creates a new HDRCubeTextureAssetTask object
  87826. * @param name defines the name of the task
  87827. * @param url defines the location of the file to load
  87828. * @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.
  87829. * @param noMipmap defines if mipmaps should not be generated (default is false)
  87830. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  87831. * @param useInGammaSpace specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)
  87832. * @param usePMREMGenerator specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  87833. */
  87834. function HDRCubeTextureAssetTask(
  87835. /**
  87836. * Defines the name of the task
  87837. */
  87838. name,
  87839. /**
  87840. * Defines the location of the file to load
  87841. */
  87842. url,
  87843. /**
  87844. * 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.
  87845. */
  87846. size,
  87847. /**
  87848. * Defines if mipmaps should not be generated (default is false)
  87849. */
  87850. noMipmap,
  87851. /**
  87852. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  87853. */
  87854. generateHarmonics,
  87855. /**
  87856. * 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)
  87857. */
  87858. useInGammaSpace,
  87859. /**
  87860. * Specifies whether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time (default is false)
  87861. */
  87862. usePMREMGenerator) {
  87863. if (noMipmap === void 0) { noMipmap = false; }
  87864. if (generateHarmonics === void 0) { generateHarmonics = true; }
  87865. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  87866. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  87867. var _this = _super.call(this, name) || this;
  87868. _this.name = name;
  87869. _this.url = url;
  87870. _this.size = size;
  87871. _this.noMipmap = noMipmap;
  87872. _this.generateHarmonics = generateHarmonics;
  87873. _this.useInGammaSpace = useInGammaSpace;
  87874. _this.usePMREMGenerator = usePMREMGenerator;
  87875. return _this;
  87876. }
  87877. /**
  87878. * Execute the current task
  87879. * @param scene defines the scene where you want your assets to be loaded
  87880. * @param onSuccess is a callback called when the task is successfully executed
  87881. * @param onError is a callback called if an error occurs
  87882. */
  87883. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  87884. var onload = function () {
  87885. onSuccess();
  87886. };
  87887. var onerror = function (message, exception) {
  87888. onError(message, exception);
  87889. };
  87890. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  87891. };
  87892. return HDRCubeTextureAssetTask;
  87893. }(AbstractAssetTask));
  87894. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  87895. /**
  87896. * This class can be used to easily import assets into a scene
  87897. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  87898. */
  87899. var AssetsManager = /** @class */ (function () {
  87900. /**
  87901. * Creates a new AssetsManager
  87902. * @param scene defines the scene to work on
  87903. */
  87904. function AssetsManager(scene) {
  87905. this._isLoading = false;
  87906. this._tasks = new Array();
  87907. this._waitingTasksCount = 0;
  87908. this._totalTasksCount = 0;
  87909. /**
  87910. * Observable called when all tasks are processed
  87911. */
  87912. this.onTaskSuccessObservable = new BABYLON.Observable();
  87913. /**
  87914. * Observable called when a task had an error
  87915. */
  87916. this.onTaskErrorObservable = new BABYLON.Observable();
  87917. /**
  87918. * Observable called when a task is successful
  87919. */
  87920. this.onTasksDoneObservable = new BABYLON.Observable();
  87921. /**
  87922. * Observable called when a task is done (whatever the result is)
  87923. */
  87924. this.onProgressObservable = new BABYLON.Observable();
  87925. /**
  87926. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  87927. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  87928. */
  87929. this.useDefaultLoadingScreen = true;
  87930. this._scene = scene;
  87931. }
  87932. /**
  87933. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  87934. * @param taskName defines the name of the new task
  87935. * @param meshesNames defines the name of meshes to load
  87936. * @param rootUrl defines the root url to use to locate files
  87937. * @param sceneFilename defines the filename of the scene file
  87938. * @returns a new {BABYLON.MeshAssetTask} object
  87939. */
  87940. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  87941. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  87942. this._tasks.push(task);
  87943. return task;
  87944. };
  87945. /**
  87946. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  87947. * @param taskName defines the name of the new task
  87948. * @param url defines the url of the file to load
  87949. * @returns a new {BABYLON.TextFileAssetTask} object
  87950. */
  87951. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  87952. var task = new TextFileAssetTask(taskName, url);
  87953. this._tasks.push(task);
  87954. return task;
  87955. };
  87956. /**
  87957. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  87958. * @param taskName defines the name of the new task
  87959. * @param url defines the url of the file to load
  87960. * @returns a new {BABYLON.BinaryFileAssetTask} object
  87961. */
  87962. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  87963. var task = new BinaryFileAssetTask(taskName, url);
  87964. this._tasks.push(task);
  87965. return task;
  87966. };
  87967. /**
  87968. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  87969. * @param taskName defines the name of the new task
  87970. * @param url defines the url of the file to load
  87971. * @returns a new {BABYLON.ImageAssetTask} object
  87972. */
  87973. AssetsManager.prototype.addImageTask = function (taskName, url) {
  87974. var task = new ImageAssetTask(taskName, url);
  87975. this._tasks.push(task);
  87976. return task;
  87977. };
  87978. /**
  87979. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  87980. * @param taskName defines the name of the new task
  87981. * @param url defines the url of the file to load
  87982. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  87983. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  87984. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  87985. * @returns a new {BABYLON.TextureAssetTask} object
  87986. */
  87987. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  87988. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  87989. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  87990. this._tasks.push(task);
  87991. return task;
  87992. };
  87993. /**
  87994. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  87995. * @param taskName defines the name of the new task
  87996. * @param url defines the url of the file to load
  87997. * @param extensions defines the extension to use to load the cube map (can be null)
  87998. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  87999. * @param files defines the list of files to load (can be null)
  88000. * @returns a new {BABYLON.CubeTextureAssetTask} object
  88001. */
  88002. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  88003. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  88004. this._tasks.push(task);
  88005. return task;
  88006. };
  88007. /**
  88008. *
  88009. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  88010. * @param taskName defines the name of the new task
  88011. * @param url defines the url of the file to load
  88012. * @param size defines the size you want for the cubemap (can be null)
  88013. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  88014. * @param generateHarmonics defines if you want to automatically generate (true by default)
  88015. * @param useInGammaSpace defines if the texture must be considered in gamma space (false by default)
  88016. * @param usePMREMGenerator is a reserved parameter and must be set to false or ignored
  88017. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  88018. */
  88019. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  88020. if (noMipmap === void 0) { noMipmap = false; }
  88021. if (generateHarmonics === void 0) { generateHarmonics = true; }
  88022. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  88023. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  88024. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  88025. this._tasks.push(task);
  88026. return task;
  88027. };
  88028. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  88029. var _this = this;
  88030. this._waitingTasksCount--;
  88031. try {
  88032. if (task.taskState === AssetTaskState.DONE) {
  88033. // Let's remove successfull tasks
  88034. BABYLON.Tools.SetImmediate(function () {
  88035. var index = _this._tasks.indexOf(task);
  88036. if (index > -1) {
  88037. _this._tasks.splice(index, 1);
  88038. }
  88039. });
  88040. }
  88041. if (this.onProgress) {
  88042. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  88043. }
  88044. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  88045. }
  88046. catch (e) {
  88047. BABYLON.Tools.Error("Error running progress callbacks.");
  88048. console.log(e);
  88049. }
  88050. if (this._waitingTasksCount === 0) {
  88051. try {
  88052. if (this.onFinish) {
  88053. this.onFinish(this._tasks);
  88054. }
  88055. this.onTasksDoneObservable.notifyObservers(this._tasks);
  88056. }
  88057. catch (e) {
  88058. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  88059. console.log(e);
  88060. }
  88061. this._isLoading = false;
  88062. this._scene.getEngine().hideLoadingUI();
  88063. }
  88064. };
  88065. AssetsManager.prototype._runTask = function (task) {
  88066. var _this = this;
  88067. var done = function () {
  88068. try {
  88069. if (_this.onTaskSuccess) {
  88070. _this.onTaskSuccess(task);
  88071. }
  88072. _this.onTaskSuccessObservable.notifyObservers(task);
  88073. _this._decreaseWaitingTasksCount(task);
  88074. }
  88075. catch (e) {
  88076. error("Error executing task success callbacks", e);
  88077. }
  88078. };
  88079. var error = function (message, exception) {
  88080. task._setErrorObject(message, exception);
  88081. if (_this.onTaskError) {
  88082. _this.onTaskError(task);
  88083. }
  88084. _this.onTaskErrorObservable.notifyObservers(task);
  88085. _this._decreaseWaitingTasksCount(task);
  88086. };
  88087. task.run(this._scene, done, error);
  88088. };
  88089. /**
  88090. * Reset the {BABYLON.AssetsManager} and remove all tasks
  88091. * @return the current instance of the {BABYLON.AssetsManager}
  88092. */
  88093. AssetsManager.prototype.reset = function () {
  88094. this._isLoading = false;
  88095. this._tasks = new Array();
  88096. return this;
  88097. };
  88098. /**
  88099. * Start the loading process
  88100. * @return the current instance of the {BABYLON.AssetsManager}
  88101. */
  88102. AssetsManager.prototype.load = function () {
  88103. if (this._isLoading) {
  88104. return this;
  88105. }
  88106. this._isLoading = true;
  88107. this._waitingTasksCount = this._tasks.length;
  88108. this._totalTasksCount = this._tasks.length;
  88109. if (this._waitingTasksCount === 0) {
  88110. this._isLoading = false;
  88111. if (this.onFinish) {
  88112. this.onFinish(this._tasks);
  88113. }
  88114. this.onTasksDoneObservable.notifyObservers(this._tasks);
  88115. return this;
  88116. }
  88117. if (this.useDefaultLoadingScreen) {
  88118. this._scene.getEngine().displayLoadingUI();
  88119. }
  88120. for (var index = 0; index < this._tasks.length; index++) {
  88121. var task = this._tasks[index];
  88122. this._runTask(task);
  88123. }
  88124. return this;
  88125. };
  88126. return AssetsManager;
  88127. }());
  88128. BABYLON.AssetsManager = AssetsManager;
  88129. })(BABYLON || (BABYLON = {}));
  88130. //# sourceMappingURL=babylon.assetsManager.js.map
  88131. "use strict";
  88132. var BABYLON;
  88133. (function (BABYLON) {
  88134. var serializedGeometries = [];
  88135. var serializeGeometry = function (geometry, serializationGeometries) {
  88136. if (serializedGeometries[geometry.id]) {
  88137. return;
  88138. }
  88139. if (geometry.doNotSerialize) {
  88140. return;
  88141. }
  88142. if (geometry instanceof BABYLON.BoxGeometry) {
  88143. serializationGeometries.boxes.push(geometry.serialize());
  88144. }
  88145. else if (geometry instanceof BABYLON.SphereGeometry) {
  88146. serializationGeometries.spheres.push(geometry.serialize());
  88147. }
  88148. else if (geometry instanceof BABYLON.CylinderGeometry) {
  88149. serializationGeometries.cylinders.push(geometry.serialize());
  88150. }
  88151. else if (geometry instanceof BABYLON.TorusGeometry) {
  88152. serializationGeometries.toruses.push(geometry.serialize());
  88153. }
  88154. else if (geometry instanceof BABYLON.GroundGeometry) {
  88155. serializationGeometries.grounds.push(geometry.serialize());
  88156. }
  88157. else if (geometry instanceof BABYLON.Plane) {
  88158. serializationGeometries.planes.push(geometry.serialize());
  88159. }
  88160. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  88161. serializationGeometries.torusKnots.push(geometry.serialize());
  88162. }
  88163. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  88164. throw new Error("Unknown primitive type");
  88165. }
  88166. else {
  88167. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  88168. }
  88169. serializedGeometries[geometry.id] = true;
  88170. };
  88171. var serializeMesh = function (mesh, serializationScene) {
  88172. var serializationObject = {};
  88173. // Geometry
  88174. var geometry = mesh._geometry;
  88175. if (geometry) {
  88176. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  88177. // 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
  88178. serializeGeometry(geometry, serializationScene.geometries);
  88179. }
  88180. }
  88181. // Custom
  88182. if (mesh.serialize) {
  88183. mesh.serialize(serializationObject);
  88184. }
  88185. return serializationObject;
  88186. };
  88187. var finalizeSingleMesh = function (mesh, serializationObject) {
  88188. //only works if the mesh is already loaded
  88189. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  88190. //serialize material
  88191. if (mesh.material) {
  88192. if (mesh.material instanceof BABYLON.StandardMaterial) {
  88193. serializationObject.materials = serializationObject.materials || [];
  88194. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  88195. serializationObject.materials.push(mesh.material.serialize());
  88196. }
  88197. }
  88198. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  88199. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  88200. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  88201. serializationObject.multiMaterials.push(mesh.material.serialize());
  88202. }
  88203. }
  88204. }
  88205. //serialize geometry
  88206. var geometry = mesh._geometry;
  88207. if (geometry) {
  88208. if (!serializationObject.geometries) {
  88209. serializationObject.geometries = {};
  88210. serializationObject.geometries.boxes = [];
  88211. serializationObject.geometries.spheres = [];
  88212. serializationObject.geometries.cylinders = [];
  88213. serializationObject.geometries.toruses = [];
  88214. serializationObject.geometries.grounds = [];
  88215. serializationObject.geometries.planes = [];
  88216. serializationObject.geometries.torusKnots = [];
  88217. serializationObject.geometries.vertexData = [];
  88218. }
  88219. serializeGeometry(geometry, serializationObject.geometries);
  88220. }
  88221. // Skeletons
  88222. if (mesh.skeleton) {
  88223. serializationObject.skeletons = serializationObject.skeletons || [];
  88224. serializationObject.skeletons.push(mesh.skeleton.serialize());
  88225. }
  88226. //serialize the actual mesh
  88227. serializationObject.meshes = serializationObject.meshes || [];
  88228. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  88229. }
  88230. };
  88231. var SceneSerializer = /** @class */ (function () {
  88232. function SceneSerializer() {
  88233. }
  88234. SceneSerializer.ClearCache = function () {
  88235. serializedGeometries = [];
  88236. };
  88237. SceneSerializer.Serialize = function (scene) {
  88238. var serializationObject = {};
  88239. SceneSerializer.ClearCache();
  88240. // Scene
  88241. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  88242. serializationObject.autoClear = scene.autoClear;
  88243. serializationObject.clearColor = scene.clearColor.asArray();
  88244. serializationObject.ambientColor = scene.ambientColor.asArray();
  88245. serializationObject.gravity = scene.gravity.asArray();
  88246. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  88247. serializationObject.workerCollisions = scene.workerCollisions;
  88248. // Fog
  88249. if (scene.fogMode && scene.fogMode !== 0) {
  88250. serializationObject.fogMode = scene.fogMode;
  88251. serializationObject.fogColor = scene.fogColor.asArray();
  88252. serializationObject.fogStart = scene.fogStart;
  88253. serializationObject.fogEnd = scene.fogEnd;
  88254. serializationObject.fogDensity = scene.fogDensity;
  88255. }
  88256. //Physics
  88257. if (scene.isPhysicsEnabled()) {
  88258. var physicEngine = scene.getPhysicsEngine();
  88259. if (physicEngine) {
  88260. serializationObject.physicsEnabled = true;
  88261. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  88262. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  88263. }
  88264. }
  88265. // Metadata
  88266. if (scene.metadata) {
  88267. serializationObject.metadata = scene.metadata;
  88268. }
  88269. // Morph targets
  88270. serializationObject.morphTargetManagers = [];
  88271. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  88272. var abstractMesh = _a[_i];
  88273. var manager = abstractMesh.morphTargetManager;
  88274. if (manager) {
  88275. serializationObject.morphTargetManagers.push(manager.serialize());
  88276. }
  88277. }
  88278. // Lights
  88279. serializationObject.lights = [];
  88280. var index;
  88281. var light;
  88282. for (index = 0; index < scene.lights.length; index++) {
  88283. light = scene.lights[index];
  88284. if (!light.doNotSerialize) {
  88285. serializationObject.lights.push(light.serialize());
  88286. }
  88287. }
  88288. // Cameras
  88289. serializationObject.cameras = [];
  88290. for (index = 0; index < scene.cameras.length; index++) {
  88291. var camera = scene.cameras[index];
  88292. if (!camera.doNotSerialize) {
  88293. serializationObject.cameras.push(camera.serialize());
  88294. }
  88295. }
  88296. if (scene.activeCamera) {
  88297. serializationObject.activeCameraID = scene.activeCamera.id;
  88298. }
  88299. // Animations
  88300. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  88301. // Materials
  88302. serializationObject.materials = [];
  88303. serializationObject.multiMaterials = [];
  88304. var material;
  88305. for (index = 0; index < scene.materials.length; index++) {
  88306. material = scene.materials[index];
  88307. if (!material.doNotSerialize) {
  88308. serializationObject.materials.push(material.serialize());
  88309. }
  88310. }
  88311. // MultiMaterials
  88312. serializationObject.multiMaterials = [];
  88313. for (index = 0; index < scene.multiMaterials.length; index++) {
  88314. var multiMaterial = scene.multiMaterials[index];
  88315. serializationObject.multiMaterials.push(multiMaterial.serialize());
  88316. }
  88317. // Environment texture
  88318. if (scene.environmentTexture) {
  88319. serializationObject.environmentTexture = scene.environmentTexture.name;
  88320. }
  88321. // Skeletons
  88322. serializationObject.skeletons = [];
  88323. for (index = 0; index < scene.skeletons.length; index++) {
  88324. var skeleton = scene.skeletons[index];
  88325. if (!skeleton.doNotSerialize) {
  88326. serializationObject.skeletons.push(skeleton.serialize());
  88327. }
  88328. }
  88329. // Transform nodes
  88330. serializationObject.transformNodes = [];
  88331. for (index = 0; index < scene.transformNodes.length; index++) {
  88332. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  88333. }
  88334. // Geometries
  88335. serializationObject.geometries = {};
  88336. serializationObject.geometries.boxes = [];
  88337. serializationObject.geometries.spheres = [];
  88338. serializationObject.geometries.cylinders = [];
  88339. serializationObject.geometries.toruses = [];
  88340. serializationObject.geometries.grounds = [];
  88341. serializationObject.geometries.planes = [];
  88342. serializationObject.geometries.torusKnots = [];
  88343. serializationObject.geometries.vertexData = [];
  88344. serializedGeometries = [];
  88345. var geometries = scene.getGeometries();
  88346. for (index = 0; index < geometries.length; index++) {
  88347. var geometry = geometries[index];
  88348. if (geometry.isReady()) {
  88349. serializeGeometry(geometry, serializationObject.geometries);
  88350. }
  88351. }
  88352. // Meshes
  88353. serializationObject.meshes = [];
  88354. for (index = 0; index < scene.meshes.length; index++) {
  88355. var abstractMesh = scene.meshes[index];
  88356. if (abstractMesh instanceof BABYLON.Mesh) {
  88357. var mesh = abstractMesh;
  88358. if (!mesh.doNotSerialize) {
  88359. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  88360. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  88361. }
  88362. }
  88363. }
  88364. }
  88365. // Particles Systems
  88366. serializationObject.particleSystems = [];
  88367. for (index = 0; index < scene.particleSystems.length; index++) {
  88368. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  88369. }
  88370. // Lens flares
  88371. serializationObject.lensFlareSystems = [];
  88372. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  88373. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  88374. }
  88375. // Shadows
  88376. serializationObject.shadowGenerators = [];
  88377. for (index = 0; index < scene.lights.length; index++) {
  88378. light = scene.lights[index];
  88379. var shadowGenerator = light.getShadowGenerator();
  88380. if (shadowGenerator) {
  88381. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  88382. }
  88383. }
  88384. // Action Manager
  88385. if (scene.actionManager) {
  88386. serializationObject.actions = scene.actionManager.serialize("scene");
  88387. }
  88388. // Audio
  88389. serializationObject.sounds = [];
  88390. for (index = 0; index < scene.soundTracks.length; index++) {
  88391. var soundtrack = scene.soundTracks[index];
  88392. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  88393. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  88394. }
  88395. }
  88396. return serializationObject;
  88397. };
  88398. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  88399. if (withParents === void 0) { withParents = false; }
  88400. if (withChildren === void 0) { withChildren = false; }
  88401. var serializationObject = {};
  88402. SceneSerializer.ClearCache();
  88403. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  88404. if (withParents || withChildren) {
  88405. //deliberate for loop! not for each, appended should be processed as well.
  88406. for (var i = 0; i < toSerialize.length; ++i) {
  88407. if (withChildren) {
  88408. toSerialize[i].getDescendants().forEach(function (node) {
  88409. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  88410. toSerialize.push(node);
  88411. }
  88412. });
  88413. }
  88414. //make sure the array doesn't contain the object already
  88415. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  88416. toSerialize.push(toSerialize[i].parent);
  88417. }
  88418. }
  88419. }
  88420. toSerialize.forEach(function (mesh) {
  88421. finalizeSingleMesh(mesh, serializationObject);
  88422. });
  88423. return serializationObject;
  88424. };
  88425. return SceneSerializer;
  88426. }());
  88427. BABYLON.SceneSerializer = SceneSerializer;
  88428. })(BABYLON || (BABYLON = {}));
  88429. //# sourceMappingURL=babylon.sceneSerializer.js.map
  88430. "use strict";
  88431. var BABYLON;
  88432. (function (BABYLON) {
  88433. var ReflectionProbe = /** @class */ (function () {
  88434. function ReflectionProbe(name, size, scene, generateMipMaps) {
  88435. if (generateMipMaps === void 0) { generateMipMaps = true; }
  88436. var _this = this;
  88437. this.name = name;
  88438. this._viewMatrix = BABYLON.Matrix.Identity();
  88439. this._target = BABYLON.Vector3.Zero();
  88440. this._add = BABYLON.Vector3.Zero();
  88441. this._invertYAxis = false;
  88442. this.position = BABYLON.Vector3.Zero();
  88443. this._scene = scene;
  88444. this._scene.reflectionProbes.push(this);
  88445. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  88446. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  88447. switch (faceIndex) {
  88448. case 0:
  88449. _this._add.copyFromFloats(1, 0, 0);
  88450. break;
  88451. case 1:
  88452. _this._add.copyFromFloats(-1, 0, 0);
  88453. break;
  88454. case 2:
  88455. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  88456. break;
  88457. case 3:
  88458. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  88459. break;
  88460. case 4:
  88461. _this._add.copyFromFloats(0, 0, 1);
  88462. break;
  88463. case 5:
  88464. _this._add.copyFromFloats(0, 0, -1);
  88465. break;
  88466. }
  88467. if (_this._attachedMesh) {
  88468. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  88469. }
  88470. _this.position.addToRef(_this._add, _this._target);
  88471. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  88472. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  88473. scene._forcedViewPosition = _this.position;
  88474. });
  88475. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  88476. scene._forcedViewPosition = null;
  88477. scene.updateTransformMatrix(true);
  88478. });
  88479. if (scene.activeCamera) {
  88480. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  88481. }
  88482. }
  88483. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  88484. get: function () {
  88485. return this._renderTargetTexture.samples;
  88486. },
  88487. set: function (value) {
  88488. this._renderTargetTexture.samples = value;
  88489. },
  88490. enumerable: true,
  88491. configurable: true
  88492. });
  88493. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  88494. get: function () {
  88495. return this._renderTargetTexture.refreshRate;
  88496. },
  88497. set: function (value) {
  88498. this._renderTargetTexture.refreshRate = value;
  88499. },
  88500. enumerable: true,
  88501. configurable: true
  88502. });
  88503. ReflectionProbe.prototype.getScene = function () {
  88504. return this._scene;
  88505. };
  88506. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  88507. get: function () {
  88508. return this._renderTargetTexture;
  88509. },
  88510. enumerable: true,
  88511. configurable: true
  88512. });
  88513. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  88514. get: function () {
  88515. return this._renderTargetTexture.renderList;
  88516. },
  88517. enumerable: true,
  88518. configurable: true
  88519. });
  88520. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  88521. this._attachedMesh = mesh;
  88522. };
  88523. /**
  88524. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  88525. *
  88526. * @param renderingGroupId The rendering group id corresponding to its index
  88527. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  88528. */
  88529. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  88530. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  88531. };
  88532. ReflectionProbe.prototype.dispose = function () {
  88533. var index = this._scene.reflectionProbes.indexOf(this);
  88534. if (index !== -1) {
  88535. // Remove from the scene if found
  88536. this._scene.reflectionProbes.splice(index, 1);
  88537. }
  88538. if (this._renderTargetTexture) {
  88539. this._renderTargetTexture.dispose();
  88540. this._renderTargetTexture = null;
  88541. }
  88542. };
  88543. return ReflectionProbe;
  88544. }());
  88545. BABYLON.ReflectionProbe = ReflectionProbe;
  88546. })(BABYLON || (BABYLON = {}));
  88547. //# sourceMappingURL=babylon.reflectionProbe.js.map
  88548. "use strict";
  88549. var BABYLON;
  88550. (function (BABYLON) {
  88551. var Layer = /** @class */ (function () {
  88552. function Layer(name, imgUrl, scene, isBackground, color) {
  88553. this.name = name;
  88554. this.scale = new BABYLON.Vector2(1, 1);
  88555. this.offset = new BABYLON.Vector2(0, 0);
  88556. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  88557. this.layerMask = 0x0FFFFFFF;
  88558. this._vertexBuffers = {};
  88559. // Events
  88560. /**
  88561. * An event triggered when the layer is disposed.
  88562. * @type {BABYLON.Observable}
  88563. */
  88564. this.onDisposeObservable = new BABYLON.Observable();
  88565. /**
  88566. * An event triggered before rendering the scene
  88567. * @type {BABYLON.Observable}
  88568. */
  88569. this.onBeforeRenderObservable = new BABYLON.Observable();
  88570. /**
  88571. * An event triggered after rendering the scene
  88572. * @type {BABYLON.Observable}
  88573. */
  88574. this.onAfterRenderObservable = new BABYLON.Observable();
  88575. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  88576. this.isBackground = isBackground === undefined ? true : isBackground;
  88577. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  88578. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  88579. this._scene.layers.push(this);
  88580. var engine = this._scene.getEngine();
  88581. // VBO
  88582. var vertices = [];
  88583. vertices.push(1, 1);
  88584. vertices.push(-1, 1);
  88585. vertices.push(-1, -1);
  88586. vertices.push(1, -1);
  88587. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  88588. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  88589. this._createIndexBuffer();
  88590. // Effects
  88591. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  88592. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  88593. }
  88594. Object.defineProperty(Layer.prototype, "onDispose", {
  88595. set: function (callback) {
  88596. if (this._onDisposeObserver) {
  88597. this.onDisposeObservable.remove(this._onDisposeObserver);
  88598. }
  88599. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  88600. },
  88601. enumerable: true,
  88602. configurable: true
  88603. });
  88604. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  88605. set: function (callback) {
  88606. if (this._onBeforeRenderObserver) {
  88607. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  88608. }
  88609. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  88610. },
  88611. enumerable: true,
  88612. configurable: true
  88613. });
  88614. Object.defineProperty(Layer.prototype, "onAfterRender", {
  88615. set: function (callback) {
  88616. if (this._onAfterRenderObserver) {
  88617. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  88618. }
  88619. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  88620. },
  88621. enumerable: true,
  88622. configurable: true
  88623. });
  88624. Layer.prototype._createIndexBuffer = function () {
  88625. var engine = this._scene.getEngine();
  88626. // Indices
  88627. var indices = [];
  88628. indices.push(0);
  88629. indices.push(1);
  88630. indices.push(2);
  88631. indices.push(0);
  88632. indices.push(2);
  88633. indices.push(3);
  88634. this._indexBuffer = engine.createIndexBuffer(indices);
  88635. };
  88636. Layer.prototype._rebuild = function () {
  88637. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  88638. if (vb) {
  88639. vb._rebuild();
  88640. }
  88641. this._createIndexBuffer();
  88642. };
  88643. Layer.prototype.render = function () {
  88644. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  88645. // Check
  88646. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  88647. return;
  88648. var engine = this._scene.getEngine();
  88649. this.onBeforeRenderObservable.notifyObservers(this);
  88650. // Render
  88651. engine.enableEffect(currentEffect);
  88652. engine.setState(false);
  88653. // Texture
  88654. currentEffect.setTexture("textureSampler", this.texture);
  88655. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  88656. // Color
  88657. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  88658. // Scale / offset
  88659. currentEffect.setVector2("offset", this.offset);
  88660. currentEffect.setVector2("scale", this.scale);
  88661. // VBOs
  88662. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  88663. // Draw order
  88664. if (!this.alphaTest) {
  88665. engine.setAlphaMode(this.alphaBlendingMode);
  88666. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  88667. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  88668. }
  88669. else {
  88670. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  88671. }
  88672. this.onAfterRenderObservable.notifyObservers(this);
  88673. };
  88674. Layer.prototype.dispose = function () {
  88675. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  88676. if (vertexBuffer) {
  88677. vertexBuffer.dispose();
  88678. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  88679. }
  88680. if (this._indexBuffer) {
  88681. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  88682. this._indexBuffer = null;
  88683. }
  88684. if (this.texture) {
  88685. this.texture.dispose();
  88686. this.texture = null;
  88687. }
  88688. // Remove from scene
  88689. var index = this._scene.layers.indexOf(this);
  88690. this._scene.layers.splice(index, 1);
  88691. // Callback
  88692. this.onDisposeObservable.notifyObservers(this);
  88693. this.onDisposeObservable.clear();
  88694. this.onAfterRenderObservable.clear();
  88695. this.onBeforeRenderObservable.clear();
  88696. };
  88697. return Layer;
  88698. }());
  88699. BABYLON.Layer = Layer;
  88700. })(BABYLON || (BABYLON = {}));
  88701. //# sourceMappingURL=babylon.layer.js.map
  88702. "use strict";
  88703. var BABYLON;
  88704. (function (BABYLON) {
  88705. var TextureTools = /** @class */ (function () {
  88706. function TextureTools() {
  88707. }
  88708. /**
  88709. * Uses the GPU to create a copy texture rescaled at a given size
  88710. * @param texture Texture to copy from
  88711. * @param width Desired width
  88712. * @param height Desired height
  88713. * @return Generated texture
  88714. */
  88715. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  88716. if (useBilinearMode === void 0) { useBilinearMode = true; }
  88717. var scene = texture.getScene();
  88718. var engine = scene.getEngine();
  88719. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  88720. rtt.wrapU = texture.wrapU;
  88721. rtt.wrapV = texture.wrapV;
  88722. rtt.uOffset = texture.uOffset;
  88723. rtt.vOffset = texture.vOffset;
  88724. rtt.uScale = texture.uScale;
  88725. rtt.vScale = texture.vScale;
  88726. rtt.uAng = texture.uAng;
  88727. rtt.vAng = texture.vAng;
  88728. rtt.wAng = texture.wAng;
  88729. rtt.coordinatesIndex = texture.coordinatesIndex;
  88730. rtt.level = texture.level;
  88731. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  88732. rtt._texture.isReady = false;
  88733. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88734. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88735. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  88736. passPostProcess.getEffect().executeWhenCompiled(function () {
  88737. passPostProcess.onApply = function (effect) {
  88738. effect.setTexture("textureSampler", texture);
  88739. };
  88740. var internalTexture = rtt.getInternalTexture();
  88741. if (internalTexture) {
  88742. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  88743. engine.unBindFramebuffer(internalTexture);
  88744. rtt.disposeFramebufferObjects();
  88745. passPostProcess.dispose();
  88746. internalTexture.isReady = true;
  88747. }
  88748. });
  88749. return rtt;
  88750. };
  88751. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  88752. if (!scene._environmentBRDFTexture) {
  88753. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  88754. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88755. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  88756. scene._environmentBRDFTexture = texture;
  88757. }
  88758. return scene._environmentBRDFTexture;
  88759. };
  88760. 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=";
  88761. return TextureTools;
  88762. }());
  88763. BABYLON.TextureTools = TextureTools;
  88764. })(BABYLON || (BABYLON = {}));
  88765. //# sourceMappingURL=babylon.textureTools.js.map
  88766. "use strict";
  88767. var BABYLON;
  88768. (function (BABYLON) {
  88769. var FramingBehavior = /** @class */ (function () {
  88770. function FramingBehavior() {
  88771. this._mode = FramingBehavior.FitFrustumSidesMode;
  88772. this._radiusScale = 1.0;
  88773. this._positionScale = 0.5;
  88774. this._defaultElevation = 0.3;
  88775. this._elevationReturnTime = 1500;
  88776. this._elevationReturnWaitTime = 1000;
  88777. this._zoomStopsAnimation = false;
  88778. this._framingTime = 1500;
  88779. this._isPointerDown = false;
  88780. this._lastInteractionTime = -Infinity;
  88781. // Framing control
  88782. this._animatables = new Array();
  88783. this._betaIsAnimating = false;
  88784. }
  88785. Object.defineProperty(FramingBehavior.prototype, "name", {
  88786. get: function () {
  88787. return "Framing";
  88788. },
  88789. enumerable: true,
  88790. configurable: true
  88791. });
  88792. Object.defineProperty(FramingBehavior.prototype, "mode", {
  88793. /**
  88794. * Gets current mode used by the behavior.
  88795. */
  88796. get: function () {
  88797. return this._mode;
  88798. },
  88799. /**
  88800. * Sets the current mode used by the behavior
  88801. */
  88802. set: function (mode) {
  88803. this._mode = mode;
  88804. },
  88805. enumerable: true,
  88806. configurable: true
  88807. });
  88808. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  88809. /**
  88810. * Gets the scale applied to the radius
  88811. */
  88812. get: function () {
  88813. return this._radiusScale;
  88814. },
  88815. /**
  88816. * Sets the scale applied to the radius (1 by default)
  88817. */
  88818. set: function (radius) {
  88819. this._radiusScale = radius;
  88820. },
  88821. enumerable: true,
  88822. configurable: true
  88823. });
  88824. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  88825. /**
  88826. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  88827. */
  88828. get: function () {
  88829. return this._positionScale;
  88830. },
  88831. /**
  88832. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  88833. */
  88834. set: function (scale) {
  88835. this._positionScale = scale;
  88836. },
  88837. enumerable: true,
  88838. configurable: true
  88839. });
  88840. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  88841. /**
  88842. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  88843. * behaviour is triggered, in radians.
  88844. */
  88845. get: function () {
  88846. return this._defaultElevation;
  88847. },
  88848. /**
  88849. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  88850. * behaviour is triggered, in radians.
  88851. */
  88852. set: function (elevation) {
  88853. this._defaultElevation = elevation;
  88854. },
  88855. enumerable: true,
  88856. configurable: true
  88857. });
  88858. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  88859. /**
  88860. * Gets the time (in milliseconds) taken to return to the default beta position.
  88861. * Negative value indicates camera should not return to default.
  88862. */
  88863. get: function () {
  88864. return this._elevationReturnTime;
  88865. },
  88866. /**
  88867. * Sets the time (in milliseconds) taken to return to the default beta position.
  88868. * Negative value indicates camera should not return to default.
  88869. */
  88870. set: function (speed) {
  88871. this._elevationReturnTime = speed;
  88872. },
  88873. enumerable: true,
  88874. configurable: true
  88875. });
  88876. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  88877. /**
  88878. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  88879. */
  88880. get: function () {
  88881. return this._elevationReturnWaitTime;
  88882. },
  88883. /**
  88884. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  88885. */
  88886. set: function (time) {
  88887. this._elevationReturnWaitTime = time;
  88888. },
  88889. enumerable: true,
  88890. configurable: true
  88891. });
  88892. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  88893. /**
  88894. * Gets the flag that indicates if user zooming should stop animation.
  88895. */
  88896. get: function () {
  88897. return this._zoomStopsAnimation;
  88898. },
  88899. /**
  88900. * Sets the flag that indicates if user zooming should stop animation.
  88901. */
  88902. set: function (flag) {
  88903. this._zoomStopsAnimation = flag;
  88904. },
  88905. enumerable: true,
  88906. configurable: true
  88907. });
  88908. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  88909. /**
  88910. * Gets the transition time when framing the mesh, in milliseconds
  88911. */
  88912. get: function () {
  88913. return this._framingTime;
  88914. },
  88915. /**
  88916. * Sets the transition time when framing the mesh, in milliseconds
  88917. */
  88918. set: function (time) {
  88919. this._framingTime = time;
  88920. },
  88921. enumerable: true,
  88922. configurable: true
  88923. });
  88924. FramingBehavior.prototype.init = function () {
  88925. // Do notihng
  88926. };
  88927. FramingBehavior.prototype.attach = function (camera) {
  88928. var _this = this;
  88929. this._attachedCamera = camera;
  88930. var scene = this._attachedCamera.getScene();
  88931. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  88932. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  88933. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  88934. _this._isPointerDown = true;
  88935. return;
  88936. }
  88937. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  88938. _this._isPointerDown = false;
  88939. }
  88940. });
  88941. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  88942. if (mesh) {
  88943. _this.zoomOnMesh(mesh);
  88944. }
  88945. });
  88946. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  88947. // Stop the animation if there is user interaction and the animation should stop for this interaction
  88948. _this._applyUserInteraction();
  88949. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  88950. // back to the default position after a given timeout
  88951. _this._maintainCameraAboveGround();
  88952. });
  88953. };
  88954. FramingBehavior.prototype.detach = function () {
  88955. if (!this._attachedCamera) {
  88956. return;
  88957. }
  88958. var scene = this._attachedCamera.getScene();
  88959. if (this._onPrePointerObservableObserver) {
  88960. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  88961. }
  88962. if (this._onAfterCheckInputsObserver) {
  88963. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  88964. }
  88965. if (this._onMeshTargetChangedObserver) {
  88966. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  88967. }
  88968. this._attachedCamera = null;
  88969. };
  88970. /**
  88971. * Targets the given mesh and updates zoom level accordingly.
  88972. * @param mesh The mesh to target.
  88973. * @param radius Optional. If a cached radius position already exists, overrides default.
  88974. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  88975. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  88976. * @param onAnimationEnd Callback triggered at the end of the framing animation
  88977. */
  88978. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  88979. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  88980. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  88981. mesh.computeWorldMatrix(true);
  88982. var boundingBox = mesh.getBoundingInfo().boundingBox;
  88983. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  88984. };
  88985. /**
  88986. * Targets the given mesh with its children and updates zoom level accordingly.
  88987. * @param mesh The mesh to target.
  88988. * @param radius Optional. If a cached radius position already exists, overrides default.
  88989. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  88990. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  88991. * @param onAnimationEnd Callback triggered at the end of the framing animation
  88992. */
  88993. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  88994. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  88995. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  88996. mesh.computeWorldMatrix(true);
  88997. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  88998. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  88999. };
  89000. /**
  89001. * Targets the given meshes with their children and updates zoom level accordingly.
  89002. * @param meshes The mesh to target.
  89003. * @param radius Optional. If a cached radius position already exists, overrides default.
  89004. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  89005. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  89006. * @param onAnimationEnd Callback triggered at the end of the framing animation
  89007. */
  89008. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  89009. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  89010. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  89011. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  89012. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  89013. for (var i = 0; i < meshes.length; i++) {
  89014. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  89015. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  89016. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  89017. }
  89018. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  89019. };
  89020. /**
  89021. * Targets the given mesh and updates zoom level accordingly.
  89022. * @param mesh The mesh to target.
  89023. * @param radius Optional. If a cached radius position already exists, overrides default.
  89024. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  89025. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  89026. * @param onAnimationEnd Callback triggered at the end of the framing animation
  89027. */
  89028. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  89029. var _this = this;
  89030. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  89031. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  89032. var zoomTarget;
  89033. if (!this._attachedCamera) {
  89034. return;
  89035. }
  89036. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  89037. var bottom = minimumWorld.y;
  89038. var top = maximumWorld.y;
  89039. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  89040. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  89041. if (focusOnOriginXZ) {
  89042. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  89043. }
  89044. else {
  89045. var centerWorld = minimumWorld.add(radiusWorld);
  89046. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  89047. }
  89048. if (!this._vectorTransition) {
  89049. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  89050. }
  89051. this._betaIsAnimating = true;
  89052. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  89053. if (animatable) {
  89054. this._animatables.push(animatable);
  89055. }
  89056. // sets the radius and lower radius bounds
  89057. // Small delta ensures camera is not always at lower zoom limit.
  89058. var radius = 0;
  89059. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  89060. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  89061. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  89062. radius = position;
  89063. }
  89064. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  89065. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  89066. if (this._attachedCamera.lowerRadiusLimit === null) {
  89067. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  89068. }
  89069. }
  89070. // Set sensibilities
  89071. var extend = maximumWorld.subtract(minimumWorld).length();
  89072. this._attachedCamera.panningSensibility = 5000 / extend;
  89073. this._attachedCamera.wheelPrecision = 100 / radius;
  89074. // transition to new radius
  89075. if (!this._radiusTransition) {
  89076. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  89077. }
  89078. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  89079. _this.stopAllAnimations();
  89080. if (onAnimationEnd) {
  89081. onAnimationEnd();
  89082. }
  89083. if (_this._attachedCamera) {
  89084. _this._attachedCamera.storeState();
  89085. }
  89086. });
  89087. if (animatable) {
  89088. this._animatables.push(animatable);
  89089. }
  89090. };
  89091. /**
  89092. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  89093. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  89094. * frustum width.
  89095. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  89096. * to fully enclose the mesh in the viewing frustum.
  89097. */
  89098. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  89099. var size = maximumWorld.subtract(minimumWorld);
  89100. var boxVectorGlobalDiagonal = size.length();
  89101. var frustumSlope = this._getFrustumSlope();
  89102. // Formula for setting distance
  89103. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  89104. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  89105. // Horizon distance
  89106. var radius = radiusWithoutFraming * this._radiusScale;
  89107. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  89108. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  89109. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  89110. var camera = this._attachedCamera;
  89111. if (!camera) {
  89112. return 0;
  89113. }
  89114. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  89115. // Don't exceed the requested limit
  89116. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  89117. }
  89118. // Don't exceed the upper radius limit
  89119. if (camera.upperRadiusLimit) {
  89120. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  89121. }
  89122. return distance;
  89123. };
  89124. /**
  89125. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  89126. * is automatically returned to its default position (expected to be above ground plane).
  89127. */
  89128. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  89129. var _this = this;
  89130. if (this._elevationReturnTime < 0) {
  89131. return;
  89132. }
  89133. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  89134. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  89135. var limitBeta = Math.PI * 0.5;
  89136. // Bring the camera back up if below the ground plane
  89137. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  89138. this._betaIsAnimating = true;
  89139. //Transition to new position
  89140. this.stopAllAnimations();
  89141. if (!this._betaTransition) {
  89142. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  89143. }
  89144. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  89145. _this._clearAnimationLocks();
  89146. _this.stopAllAnimations();
  89147. });
  89148. if (animatabe) {
  89149. this._animatables.push(animatabe);
  89150. }
  89151. }
  89152. };
  89153. /**
  89154. * Returns the frustum slope based on the canvas ratio and camera FOV
  89155. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  89156. */
  89157. FramingBehavior.prototype._getFrustumSlope = function () {
  89158. // Calculate the viewport ratio
  89159. // Aspect Ratio is Height/Width.
  89160. var camera = this._attachedCamera;
  89161. if (!camera) {
  89162. return BABYLON.Vector2.Zero();
  89163. }
  89164. var engine = camera.getScene().getEngine();
  89165. var aspectRatio = engine.getAspectRatio(camera);
  89166. // Camera FOV is the vertical field of view (top-bottom) in radians.
  89167. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  89168. var frustumSlopeY = Math.tan(camera.fov / 2);
  89169. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  89170. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  89171. // along the forward vector.
  89172. var frustumSlopeX = frustumSlopeY * aspectRatio;
  89173. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  89174. };
  89175. /**
  89176. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  89177. */
  89178. FramingBehavior.prototype._clearAnimationLocks = function () {
  89179. this._betaIsAnimating = false;
  89180. };
  89181. /**
  89182. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  89183. */
  89184. FramingBehavior.prototype._applyUserInteraction = function () {
  89185. if (this.isUserIsMoving) {
  89186. this._lastInteractionTime = BABYLON.Tools.Now;
  89187. this.stopAllAnimations();
  89188. this._clearAnimationLocks();
  89189. }
  89190. };
  89191. /**
  89192. * Stops and removes all animations that have been applied to the camera
  89193. */
  89194. FramingBehavior.prototype.stopAllAnimations = function () {
  89195. if (this._attachedCamera) {
  89196. this._attachedCamera.animations = [];
  89197. }
  89198. while (this._animatables.length) {
  89199. if (this._animatables[0]) {
  89200. this._animatables[0].onAnimationEnd = null;
  89201. this._animatables[0].stop();
  89202. }
  89203. this._animatables.shift();
  89204. }
  89205. };
  89206. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  89207. /**
  89208. * Gets a value indicating if the user is moving the camera
  89209. */
  89210. get: function () {
  89211. if (!this._attachedCamera) {
  89212. return false;
  89213. }
  89214. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  89215. this._attachedCamera.inertialBetaOffset !== 0 ||
  89216. this._attachedCamera.inertialRadiusOffset !== 0 ||
  89217. this._attachedCamera.inertialPanningX !== 0 ||
  89218. this._attachedCamera.inertialPanningY !== 0 ||
  89219. this._isPointerDown;
  89220. },
  89221. enumerable: true,
  89222. configurable: true
  89223. });
  89224. /**
  89225. * The easing function used by animations
  89226. */
  89227. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  89228. /**
  89229. * The easing mode used by animations
  89230. */
  89231. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  89232. // Statics
  89233. /**
  89234. * The camera can move all the way towards the mesh.
  89235. */
  89236. FramingBehavior.IgnoreBoundsSizeMode = 0;
  89237. /**
  89238. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  89239. */
  89240. FramingBehavior.FitFrustumSidesMode = 1;
  89241. return FramingBehavior;
  89242. }());
  89243. BABYLON.FramingBehavior = FramingBehavior;
  89244. })(BABYLON || (BABYLON = {}));
  89245. //# sourceMappingURL=babylon.framingBehavior.js.map
  89246. "use strict";
  89247. var BABYLON;
  89248. (function (BABYLON) {
  89249. /**
  89250. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  89251. */
  89252. var BouncingBehavior = /** @class */ (function () {
  89253. function BouncingBehavior() {
  89254. /**
  89255. * The duration of the animation, in milliseconds
  89256. */
  89257. this.transitionDuration = 450;
  89258. /**
  89259. * Length of the distance animated by the transition when lower radius is reached
  89260. */
  89261. this.lowerRadiusTransitionRange = 2;
  89262. /**
  89263. * Length of the distance animated by the transition when upper radius is reached
  89264. */
  89265. this.upperRadiusTransitionRange = -2;
  89266. this._autoTransitionRange = false;
  89267. // Animations
  89268. this._radiusIsAnimating = false;
  89269. this._radiusBounceTransition = null;
  89270. this._animatables = new Array();
  89271. }
  89272. Object.defineProperty(BouncingBehavior.prototype, "name", {
  89273. get: function () {
  89274. return "Bouncing";
  89275. },
  89276. enumerable: true,
  89277. configurable: true
  89278. });
  89279. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  89280. /**
  89281. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  89282. */
  89283. get: function () {
  89284. return this._autoTransitionRange;
  89285. },
  89286. /**
  89287. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  89288. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  89289. */
  89290. set: function (value) {
  89291. var _this = this;
  89292. if (this._autoTransitionRange === value) {
  89293. return;
  89294. }
  89295. this._autoTransitionRange = value;
  89296. var camera = this._attachedCamera;
  89297. if (!camera) {
  89298. return;
  89299. }
  89300. if (value) {
  89301. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  89302. if (!mesh) {
  89303. return;
  89304. }
  89305. mesh.computeWorldMatrix(true);
  89306. var diagonal = mesh.getBoundingInfo().diagonalLength;
  89307. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  89308. _this.upperRadiusTransitionRange = diagonal * 0.05;
  89309. });
  89310. }
  89311. else if (this._onMeshTargetChangedObserver) {
  89312. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  89313. }
  89314. },
  89315. enumerable: true,
  89316. configurable: true
  89317. });
  89318. BouncingBehavior.prototype.init = function () {
  89319. // Do notihng
  89320. };
  89321. BouncingBehavior.prototype.attach = function (camera) {
  89322. var _this = this;
  89323. this._attachedCamera = camera;
  89324. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  89325. if (!_this._attachedCamera) {
  89326. return;
  89327. }
  89328. // Add the bounce animation to the lower radius limit
  89329. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  89330. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  89331. }
  89332. // Add the bounce animation to the upper radius limit
  89333. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  89334. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  89335. }
  89336. });
  89337. };
  89338. BouncingBehavior.prototype.detach = function () {
  89339. if (!this._attachedCamera) {
  89340. return;
  89341. }
  89342. if (this._onAfterCheckInputsObserver) {
  89343. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  89344. }
  89345. if (this._onMeshTargetChangedObserver) {
  89346. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  89347. }
  89348. this._attachedCamera = null;
  89349. };
  89350. /**
  89351. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  89352. * @param radiusLimit The limit to check against.
  89353. * @return Bool to indicate if at limit.
  89354. */
  89355. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  89356. if (!this._attachedCamera) {
  89357. return false;
  89358. }
  89359. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  89360. return true;
  89361. }
  89362. return false;
  89363. };
  89364. /**
  89365. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  89366. * @param radiusDelta The delta by which to animate to. Can be negative.
  89367. */
  89368. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  89369. var _this = this;
  89370. if (!this._attachedCamera) {
  89371. return;
  89372. }
  89373. if (!this._radiusBounceTransition) {
  89374. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  89375. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  89376. }
  89377. // Prevent zoom until bounce has completed
  89378. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  89379. this._attachedCamera.wheelPrecision = Infinity;
  89380. this._attachedCamera.inertialRadiusOffset = 0;
  89381. // Animate to the radius limit
  89382. this.stopAllAnimations();
  89383. this._radiusIsAnimating = true;
  89384. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  89385. if (animatable) {
  89386. this._animatables.push(animatable);
  89387. }
  89388. };
  89389. /**
  89390. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  89391. */
  89392. BouncingBehavior.prototype._clearAnimationLocks = function () {
  89393. this._radiusIsAnimating = false;
  89394. if (this._attachedCamera) {
  89395. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  89396. }
  89397. };
  89398. /**
  89399. * Stops and removes all animations that have been applied to the camera
  89400. */
  89401. BouncingBehavior.prototype.stopAllAnimations = function () {
  89402. if (this._attachedCamera) {
  89403. this._attachedCamera.animations = [];
  89404. }
  89405. while (this._animatables.length) {
  89406. this._animatables[0].onAnimationEnd = null;
  89407. this._animatables[0].stop();
  89408. this._animatables.shift();
  89409. }
  89410. };
  89411. /**
  89412. * The easing function used by animations
  89413. */
  89414. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  89415. /**
  89416. * The easing mode used by animations
  89417. */
  89418. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  89419. return BouncingBehavior;
  89420. }());
  89421. BABYLON.BouncingBehavior = BouncingBehavior;
  89422. })(BABYLON || (BABYLON = {}));
  89423. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  89424. "use strict";
  89425. var BABYLON;
  89426. (function (BABYLON) {
  89427. var AutoRotationBehavior = /** @class */ (function () {
  89428. function AutoRotationBehavior() {
  89429. this._zoomStopsAnimation = false;
  89430. this._idleRotationSpeed = 0.05;
  89431. this._idleRotationWaitTime = 2000;
  89432. this._idleRotationSpinupTime = 2000;
  89433. this._isPointerDown = false;
  89434. this._lastFrameTime = null;
  89435. this._lastInteractionTime = -Infinity;
  89436. this._cameraRotationSpeed = 0;
  89437. this._lastFrameRadius = 0;
  89438. }
  89439. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  89440. get: function () {
  89441. return "AutoRotation";
  89442. },
  89443. enumerable: true,
  89444. configurable: true
  89445. });
  89446. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  89447. /**
  89448. * Gets the flag that indicates if user zooming should stop animation.
  89449. */
  89450. get: function () {
  89451. return this._zoomStopsAnimation;
  89452. },
  89453. /**
  89454. * Sets the flag that indicates if user zooming should stop animation.
  89455. */
  89456. set: function (flag) {
  89457. this._zoomStopsAnimation = flag;
  89458. },
  89459. enumerable: true,
  89460. configurable: true
  89461. });
  89462. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  89463. /**
  89464. * Gets the default speed at which the camera rotates around the model.
  89465. */
  89466. get: function () {
  89467. return this._idleRotationSpeed;
  89468. },
  89469. /**
  89470. * Sets the default speed at which the camera rotates around the model.
  89471. */
  89472. set: function (speed) {
  89473. this._idleRotationSpeed = speed;
  89474. },
  89475. enumerable: true,
  89476. configurable: true
  89477. });
  89478. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  89479. /**
  89480. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  89481. */
  89482. get: function () {
  89483. return this._idleRotationWaitTime;
  89484. },
  89485. /**
  89486. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  89487. */
  89488. set: function (time) {
  89489. this._idleRotationWaitTime = time;
  89490. },
  89491. enumerable: true,
  89492. configurable: true
  89493. });
  89494. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  89495. /**
  89496. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  89497. */
  89498. get: function () {
  89499. return this._idleRotationSpinupTime;
  89500. },
  89501. /**
  89502. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  89503. */
  89504. set: function (time) {
  89505. this._idleRotationSpinupTime = time;
  89506. },
  89507. enumerable: true,
  89508. configurable: true
  89509. });
  89510. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  89511. /**
  89512. * Gets a value indicating if the camera is currently rotating because of this behavior
  89513. */
  89514. get: function () {
  89515. return Math.abs(this._cameraRotationSpeed) > 0;
  89516. },
  89517. enumerable: true,
  89518. configurable: true
  89519. });
  89520. AutoRotationBehavior.prototype.init = function () {
  89521. // Do notihng
  89522. };
  89523. AutoRotationBehavior.prototype.attach = function (camera) {
  89524. var _this = this;
  89525. this._attachedCamera = camera;
  89526. var scene = this._attachedCamera.getScene();
  89527. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  89528. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  89529. _this._isPointerDown = true;
  89530. return;
  89531. }
  89532. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  89533. _this._isPointerDown = false;
  89534. }
  89535. });
  89536. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  89537. var now = BABYLON.Tools.Now;
  89538. var dt = 0;
  89539. if (_this._lastFrameTime != null) {
  89540. dt = now - _this._lastFrameTime;
  89541. }
  89542. _this._lastFrameTime = now;
  89543. // Stop the animation if there is user interaction and the animation should stop for this interaction
  89544. _this._applyUserInteraction();
  89545. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  89546. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  89547. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  89548. // Step camera rotation by rotation speed
  89549. if (_this._attachedCamera) {
  89550. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  89551. }
  89552. });
  89553. };
  89554. AutoRotationBehavior.prototype.detach = function () {
  89555. if (!this._attachedCamera) {
  89556. return;
  89557. }
  89558. var scene = this._attachedCamera.getScene();
  89559. if (this._onPrePointerObservableObserver) {
  89560. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  89561. }
  89562. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  89563. this._attachedCamera = null;
  89564. };
  89565. /**
  89566. * Returns true if user is scrolling.
  89567. * @return true if user is scrolling.
  89568. */
  89569. AutoRotationBehavior.prototype._userIsZooming = function () {
  89570. if (!this._attachedCamera) {
  89571. return false;
  89572. }
  89573. return this._attachedCamera.inertialRadiusOffset !== 0;
  89574. };
  89575. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  89576. if (!this._attachedCamera) {
  89577. return false;
  89578. }
  89579. var zoomHasHitLimit = false;
  89580. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  89581. zoomHasHitLimit = true;
  89582. }
  89583. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  89584. this._lastFrameRadius = this._attachedCamera.radius;
  89585. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  89586. };
  89587. /**
  89588. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  89589. */
  89590. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  89591. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  89592. this._lastInteractionTime = BABYLON.Tools.Now;
  89593. }
  89594. };
  89595. // Tools
  89596. AutoRotationBehavior.prototype._userIsMoving = function () {
  89597. if (!this._attachedCamera) {
  89598. return false;
  89599. }
  89600. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  89601. this._attachedCamera.inertialBetaOffset !== 0 ||
  89602. this._attachedCamera.inertialRadiusOffset !== 0 ||
  89603. this._attachedCamera.inertialPanningX !== 0 ||
  89604. this._attachedCamera.inertialPanningY !== 0 ||
  89605. this._isPointerDown;
  89606. };
  89607. return AutoRotationBehavior;
  89608. }());
  89609. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  89610. })(BABYLON || (BABYLON = {}));
  89611. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  89612. "use strict";
  89613. var BABYLON;
  89614. (function (BABYLON) {
  89615. var NullEngineOptions = /** @class */ (function () {
  89616. function NullEngineOptions() {
  89617. this.renderWidth = 512;
  89618. this.renderHeight = 256;
  89619. this.textureSize = 512;
  89620. this.deterministicLockstep = false;
  89621. this.lockstepMaxSteps = 4;
  89622. }
  89623. return NullEngineOptions;
  89624. }());
  89625. BABYLON.NullEngineOptions = NullEngineOptions;
  89626. /**
  89627. * The null engine class provides support for headless version of babylon.js.
  89628. * This can be used in server side scenario or for testing purposes
  89629. */
  89630. var NullEngine = /** @class */ (function (_super) {
  89631. __extends(NullEngine, _super);
  89632. function NullEngine(options) {
  89633. if (options === void 0) { options = new NullEngineOptions(); }
  89634. var _this = _super.call(this, null) || this;
  89635. if (options.deterministicLockstep === undefined) {
  89636. options.deterministicLockstep = false;
  89637. }
  89638. if (options.lockstepMaxSteps === undefined) {
  89639. options.lockstepMaxSteps = 4;
  89640. }
  89641. _this._options = options;
  89642. // Init caps
  89643. // We consider we are on a webgl1 capable device
  89644. _this._caps = new BABYLON.EngineCapabilities();
  89645. _this._caps.maxTexturesImageUnits = 16;
  89646. _this._caps.maxVertexTextureImageUnits = 16;
  89647. _this._caps.maxTextureSize = 512;
  89648. _this._caps.maxCubemapTextureSize = 512;
  89649. _this._caps.maxRenderTextureSize = 512;
  89650. _this._caps.maxVertexAttribs = 16;
  89651. _this._caps.maxVaryingVectors = 16;
  89652. _this._caps.maxFragmentUniformVectors = 16;
  89653. _this._caps.maxVertexUniformVectors = 16;
  89654. // Extensions
  89655. _this._caps.standardDerivatives = false;
  89656. _this._caps.astc = null;
  89657. _this._caps.s3tc = null;
  89658. _this._caps.pvrtc = null;
  89659. _this._caps.etc1 = null;
  89660. _this._caps.etc2 = null;
  89661. _this._caps.textureAnisotropicFilterExtension = null;
  89662. _this._caps.maxAnisotropy = 0;
  89663. _this._caps.uintIndices = false;
  89664. _this._caps.fragmentDepthSupported = false;
  89665. _this._caps.highPrecisionShaderSupported = true;
  89666. _this._caps.colorBufferFloat = false;
  89667. _this._caps.textureFloat = false;
  89668. _this._caps.textureFloatLinearFiltering = false;
  89669. _this._caps.textureFloatRender = false;
  89670. _this._caps.textureHalfFloat = false;
  89671. _this._caps.textureHalfFloatLinearFiltering = false;
  89672. _this._caps.textureHalfFloatRender = false;
  89673. _this._caps.textureLOD = false;
  89674. _this._caps.drawBuffersExtension = false;
  89675. _this._caps.depthTextureExtension = false;
  89676. _this._caps.vertexArrayObject = false;
  89677. _this._caps.instancedArrays = false;
  89678. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  89679. // Wrappers
  89680. if (typeof URL === "undefined") {
  89681. URL = {
  89682. createObjectURL: function () { },
  89683. revokeObjectURL: function () { }
  89684. };
  89685. }
  89686. if (typeof Blob === "undefined") {
  89687. Blob = function () { };
  89688. }
  89689. return _this;
  89690. }
  89691. NullEngine.prototype.isDeterministicLockStep = function () {
  89692. return this._options.deterministicLockstep;
  89693. };
  89694. NullEngine.prototype.getLockstepMaxSteps = function () {
  89695. return this._options.lockstepMaxSteps;
  89696. };
  89697. NullEngine.prototype.getHardwareScalingLevel = function () {
  89698. return 1.0;
  89699. };
  89700. NullEngine.prototype.createVertexBuffer = function (vertices) {
  89701. return {
  89702. capacity: 0,
  89703. references: 1,
  89704. is32Bits: false
  89705. };
  89706. };
  89707. NullEngine.prototype.createIndexBuffer = function (indices) {
  89708. return {
  89709. capacity: 0,
  89710. references: 1,
  89711. is32Bits: false
  89712. };
  89713. };
  89714. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  89715. if (stencil === void 0) { stencil = false; }
  89716. };
  89717. NullEngine.prototype.getRenderWidth = function (useScreen) {
  89718. if (useScreen === void 0) { useScreen = false; }
  89719. if (!useScreen && this._currentRenderTarget) {
  89720. return this._currentRenderTarget.width;
  89721. }
  89722. return this._options.renderWidth;
  89723. };
  89724. NullEngine.prototype.getRenderHeight = function (useScreen) {
  89725. if (useScreen === void 0) { useScreen = false; }
  89726. if (!useScreen && this._currentRenderTarget) {
  89727. return this._currentRenderTarget.height;
  89728. }
  89729. return this._options.renderHeight;
  89730. };
  89731. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  89732. this._cachedViewport = viewport;
  89733. };
  89734. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  89735. return {
  89736. transformFeedback: null,
  89737. __SPECTOR_rebuildProgram: null
  89738. };
  89739. };
  89740. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  89741. return [];
  89742. };
  89743. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  89744. return [];
  89745. };
  89746. NullEngine.prototype.bindSamplers = function (effect) {
  89747. this._currentEffect = null;
  89748. };
  89749. NullEngine.prototype.enableEffect = function (effect) {
  89750. this._currentEffect = effect;
  89751. if (effect.onBind) {
  89752. effect.onBind(effect);
  89753. }
  89754. effect.onBindObservable.notifyObservers(effect);
  89755. };
  89756. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  89757. if (zOffset === void 0) { zOffset = 0; }
  89758. if (reverseSide === void 0) { reverseSide = false; }
  89759. };
  89760. NullEngine.prototype.setIntArray = function (uniform, array) {
  89761. };
  89762. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  89763. };
  89764. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  89765. };
  89766. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  89767. };
  89768. NullEngine.prototype.setFloatArray = function (uniform, array) {
  89769. };
  89770. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  89771. };
  89772. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  89773. };
  89774. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  89775. };
  89776. NullEngine.prototype.setArray = function (uniform, array) {
  89777. };
  89778. NullEngine.prototype.setArray2 = function (uniform, array) {
  89779. };
  89780. NullEngine.prototype.setArray3 = function (uniform, array) {
  89781. };
  89782. NullEngine.prototype.setArray4 = function (uniform, array) {
  89783. };
  89784. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  89785. };
  89786. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  89787. };
  89788. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  89789. };
  89790. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  89791. };
  89792. NullEngine.prototype.setFloat = function (uniform, value) {
  89793. };
  89794. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  89795. };
  89796. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  89797. };
  89798. NullEngine.prototype.setBool = function (uniform, bool) {
  89799. };
  89800. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  89801. };
  89802. NullEngine.prototype.setColor3 = function (uniform, color3) {
  89803. };
  89804. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  89805. };
  89806. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  89807. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  89808. if (this._alphaMode === mode) {
  89809. return;
  89810. }
  89811. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  89812. if (!noDepthWriteChange) {
  89813. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  89814. }
  89815. this._alphaMode = mode;
  89816. };
  89817. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  89818. };
  89819. NullEngine.prototype.wipeCaches = function (bruteForce) {
  89820. if (this.preventCacheWipeBetweenFrames) {
  89821. return;
  89822. }
  89823. this.resetTextureCache();
  89824. this._currentEffect = null;
  89825. if (bruteForce) {
  89826. this._currentProgram = null;
  89827. this._stencilState.reset();
  89828. this._depthCullingState.reset();
  89829. this._alphaState.reset();
  89830. }
  89831. this._cachedVertexBuffers = null;
  89832. this._cachedIndexBuffer = null;
  89833. this._cachedEffectForVertexBuffers = null;
  89834. };
  89835. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  89836. };
  89837. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  89838. };
  89839. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  89840. };
  89841. NullEngine.prototype._createTexture = function () {
  89842. return {};
  89843. };
  89844. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  89845. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  89846. if (onLoad === void 0) { onLoad = null; }
  89847. if (onError === void 0) { onError = null; }
  89848. if (buffer === void 0) { buffer = null; }
  89849. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  89850. var url = String(urlArg);
  89851. texture.url = url;
  89852. texture.generateMipMaps = !noMipmap;
  89853. texture.samplingMode = samplingMode;
  89854. texture.invertY = invertY;
  89855. texture.baseWidth = this._options.textureSize;
  89856. texture.baseHeight = this._options.textureSize;
  89857. texture.width = this._options.textureSize;
  89858. texture.height = this._options.textureSize;
  89859. if (format) {
  89860. texture.format = format;
  89861. }
  89862. texture.isReady = true;
  89863. if (onLoad) {
  89864. onLoad();
  89865. }
  89866. return texture;
  89867. };
  89868. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  89869. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  89870. if (options !== undefined && typeof options === "object") {
  89871. fullOptions.generateMipMaps = options.generateMipMaps;
  89872. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  89873. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  89874. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  89875. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  89876. }
  89877. else {
  89878. fullOptions.generateMipMaps = options;
  89879. fullOptions.generateDepthBuffer = true;
  89880. fullOptions.generateStencilBuffer = false;
  89881. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  89882. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  89883. }
  89884. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  89885. var width = size.width || size;
  89886. var height = size.height || size;
  89887. texture._depthStencilBuffer = {};
  89888. texture._framebuffer = {};
  89889. texture.baseWidth = width;
  89890. texture.baseHeight = height;
  89891. texture.width = width;
  89892. texture.height = height;
  89893. texture.isReady = true;
  89894. texture.samples = 1;
  89895. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  89896. texture.samplingMode = fullOptions.samplingMode;
  89897. texture.type = fullOptions.type;
  89898. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  89899. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  89900. return texture;
  89901. };
  89902. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  89903. texture.samplingMode = samplingMode;
  89904. };
  89905. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  89906. if (this._currentRenderTarget) {
  89907. this.unBindFramebuffer(this._currentRenderTarget);
  89908. }
  89909. this._currentRenderTarget = texture;
  89910. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  89911. if (this._cachedViewport && !forceFullscreenViewport) {
  89912. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  89913. }
  89914. };
  89915. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  89916. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  89917. this._currentRenderTarget = null;
  89918. if (onBeforeUnbind) {
  89919. if (texture._MSAAFramebuffer) {
  89920. this._currentFramebuffer = texture._framebuffer;
  89921. }
  89922. onBeforeUnbind();
  89923. }
  89924. this._currentFramebuffer = null;
  89925. };
  89926. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  89927. var vbo = {
  89928. capacity: 1,
  89929. references: 1,
  89930. is32Bits: false
  89931. };
  89932. return vbo;
  89933. };
  89934. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  89935. if (offset === void 0) { offset = 0; }
  89936. };
  89937. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  89938. };
  89939. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  89940. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  89941. this._boundTexturesCache[this._activeChannel] = texture;
  89942. }
  89943. };
  89944. NullEngine.prototype._bindTexture = function (channel, texture) {
  89945. if (channel < 0) {
  89946. return;
  89947. }
  89948. this._bindTextureDirectly(0, texture);
  89949. };
  89950. NullEngine.prototype._releaseBuffer = function (buffer) {
  89951. buffer.references--;
  89952. if (buffer.references === 0) {
  89953. return true;
  89954. }
  89955. return false;
  89956. };
  89957. return NullEngine;
  89958. }(BABYLON.Engine));
  89959. BABYLON.NullEngine = NullEngine;
  89960. })(BABYLON || (BABYLON = {}));
  89961. //# sourceMappingURL=babylon.nullEngine.js.map
  89962. "use strict";
  89963. var BABYLON;
  89964. (function (BABYLON) {
  89965. /**
  89966. * This class can be used to get instrumentation data from a Babylon engine
  89967. */
  89968. var EngineInstrumentation = /** @class */ (function () {
  89969. function EngineInstrumentation(engine) {
  89970. this.engine = engine;
  89971. this._captureGPUFrameTime = false;
  89972. this._gpuFrameTime = new BABYLON.PerfCounter();
  89973. this._captureShaderCompilationTime = false;
  89974. this._shaderCompilationTime = new BABYLON.PerfCounter();
  89975. // Observers
  89976. this._onBeginFrameObserver = null;
  89977. this._onEndFrameObserver = null;
  89978. this._onBeforeShaderCompilationObserver = null;
  89979. this._onAfterShaderCompilationObserver = null;
  89980. }
  89981. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  89982. // Properties
  89983. /**
  89984. * Gets the perf counter used for GPU frame time
  89985. */
  89986. get: function () {
  89987. return this._gpuFrameTime;
  89988. },
  89989. enumerable: true,
  89990. configurable: true
  89991. });
  89992. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  89993. /**
  89994. * Gets the GPU frame time capture status
  89995. */
  89996. get: function () {
  89997. return this._captureGPUFrameTime;
  89998. },
  89999. /**
  90000. * Enable or disable the GPU frame time capture
  90001. */
  90002. set: function (value) {
  90003. var _this = this;
  90004. if (value === this._captureGPUFrameTime) {
  90005. return;
  90006. }
  90007. this._captureGPUFrameTime = value;
  90008. if (value) {
  90009. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  90010. if (!_this._gpuFrameTimeToken) {
  90011. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  90012. }
  90013. });
  90014. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  90015. if (!_this._gpuFrameTimeToken) {
  90016. return;
  90017. }
  90018. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  90019. if (time > -1) {
  90020. _this._gpuFrameTimeToken = null;
  90021. _this._gpuFrameTime.fetchNewFrame();
  90022. _this._gpuFrameTime.addCount(time, true);
  90023. }
  90024. });
  90025. }
  90026. else {
  90027. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  90028. this._onBeginFrameObserver = null;
  90029. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  90030. this._onEndFrameObserver = null;
  90031. }
  90032. },
  90033. enumerable: true,
  90034. configurable: true
  90035. });
  90036. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  90037. /**
  90038. * Gets the perf counter used for shader compilation time
  90039. */
  90040. get: function () {
  90041. return this._shaderCompilationTime;
  90042. },
  90043. enumerable: true,
  90044. configurable: true
  90045. });
  90046. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  90047. /**
  90048. * Gets the shader compilation time capture status
  90049. */
  90050. get: function () {
  90051. return this._captureShaderCompilationTime;
  90052. },
  90053. /**
  90054. * Enable or disable the shader compilation time capture
  90055. */
  90056. set: function (value) {
  90057. var _this = this;
  90058. if (value === this._captureShaderCompilationTime) {
  90059. return;
  90060. }
  90061. this._captureShaderCompilationTime = value;
  90062. if (value) {
  90063. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  90064. _this._shaderCompilationTime.fetchNewFrame();
  90065. _this._shaderCompilationTime.beginMonitoring();
  90066. });
  90067. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  90068. _this._shaderCompilationTime.endMonitoring();
  90069. });
  90070. }
  90071. else {
  90072. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  90073. this._onBeforeShaderCompilationObserver = null;
  90074. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  90075. this._onAfterShaderCompilationObserver = null;
  90076. }
  90077. },
  90078. enumerable: true,
  90079. configurable: true
  90080. });
  90081. EngineInstrumentation.prototype.dispose = function () {
  90082. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  90083. this._onBeginFrameObserver = null;
  90084. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  90085. this._onEndFrameObserver = null;
  90086. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  90087. this._onBeforeShaderCompilationObserver = null;
  90088. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  90089. this._onAfterShaderCompilationObserver = null;
  90090. this.engine = null;
  90091. };
  90092. return EngineInstrumentation;
  90093. }());
  90094. BABYLON.EngineInstrumentation = EngineInstrumentation;
  90095. })(BABYLON || (BABYLON = {}));
  90096. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  90097. "use strict";
  90098. var BABYLON;
  90099. (function (BABYLON) {
  90100. /**
  90101. * This class can be used to get instrumentation data from a Babylon engine
  90102. */
  90103. var SceneInstrumentation = /** @class */ (function () {
  90104. function SceneInstrumentation(scene) {
  90105. var _this = this;
  90106. this.scene = scene;
  90107. this._captureActiveMeshesEvaluationTime = false;
  90108. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  90109. this._captureRenderTargetsRenderTime = false;
  90110. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  90111. this._captureFrameTime = false;
  90112. this._frameTime = new BABYLON.PerfCounter();
  90113. this._captureRenderTime = false;
  90114. this._renderTime = new BABYLON.PerfCounter();
  90115. this._captureInterFrameTime = false;
  90116. this._interFrameTime = new BABYLON.PerfCounter();
  90117. this._captureParticlesRenderTime = false;
  90118. this._particlesRenderTime = new BABYLON.PerfCounter();
  90119. this._captureSpritesRenderTime = false;
  90120. this._spritesRenderTime = new BABYLON.PerfCounter();
  90121. this._capturePhysicsTime = false;
  90122. this._physicsTime = new BABYLON.PerfCounter();
  90123. this._captureAnimationsTime = false;
  90124. this._animationsTime = new BABYLON.PerfCounter();
  90125. // Observers
  90126. this._onBeforeActiveMeshesEvaluationObserver = null;
  90127. this._onAfterActiveMeshesEvaluationObserver = null;
  90128. this._onBeforeRenderTargetsRenderObserver = null;
  90129. this._onAfterRenderTargetsRenderObserver = null;
  90130. this._onAfterRenderObserver = null;
  90131. this._onBeforeDrawPhaseObserver = null;
  90132. this._onAfterDrawPhaseObserver = null;
  90133. this._onBeforeAnimationsObserver = null;
  90134. this._onBeforeParticlesRenderingObserver = null;
  90135. this._onAfterParticlesRenderingObserver = null;
  90136. this._onBeforeSpritesRenderingObserver = null;
  90137. this._onAfterSpritesRenderingObserver = null;
  90138. this._onBeforePhysicsObserver = null;
  90139. this._onAfterPhysicsObserver = null;
  90140. this._onAfterAnimationsObserver = null;
  90141. // Before render
  90142. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  90143. if (_this._captureActiveMeshesEvaluationTime) {
  90144. _this._activeMeshesEvaluationTime.fetchNewFrame();
  90145. }
  90146. if (_this._captureRenderTargetsRenderTime) {
  90147. _this._renderTargetsRenderTime.fetchNewFrame();
  90148. }
  90149. if (_this._captureFrameTime) {
  90150. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  90151. _this._frameTime.beginMonitoring();
  90152. }
  90153. if (_this._captureInterFrameTime) {
  90154. _this._interFrameTime.endMonitoring();
  90155. }
  90156. if (_this._captureParticlesRenderTime) {
  90157. _this._particlesRenderTime.fetchNewFrame();
  90158. }
  90159. if (_this._captureSpritesRenderTime) {
  90160. _this._spritesRenderTime.fetchNewFrame();
  90161. }
  90162. if (_this._captureAnimationsTime) {
  90163. _this._animationsTime.beginMonitoring();
  90164. }
  90165. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  90166. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  90167. });
  90168. // After render
  90169. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  90170. if (_this._captureFrameTime) {
  90171. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  90172. _this._frameTime.endMonitoring();
  90173. }
  90174. if (_this._captureRenderTime) {
  90175. _this._renderTime.endMonitoring(false);
  90176. }
  90177. if (_this._captureInterFrameTime) {
  90178. _this._interFrameTime.beginMonitoring();
  90179. }
  90180. });
  90181. }
  90182. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  90183. // Properties
  90184. /**
  90185. * Gets the perf counter used for active meshes evaluation time
  90186. */
  90187. get: function () {
  90188. return this._activeMeshesEvaluationTime;
  90189. },
  90190. enumerable: true,
  90191. configurable: true
  90192. });
  90193. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  90194. /**
  90195. * Gets the active meshes evaluation time capture status
  90196. */
  90197. get: function () {
  90198. return this._captureActiveMeshesEvaluationTime;
  90199. },
  90200. /**
  90201. * Enable or disable the active meshes evaluation time capture
  90202. */
  90203. set: function (value) {
  90204. var _this = this;
  90205. if (value === this._captureActiveMeshesEvaluationTime) {
  90206. return;
  90207. }
  90208. this._captureActiveMeshesEvaluationTime = value;
  90209. if (value) {
  90210. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  90211. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  90212. _this._activeMeshesEvaluationTime.beginMonitoring();
  90213. });
  90214. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  90215. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  90216. _this._activeMeshesEvaluationTime.endMonitoring();
  90217. });
  90218. }
  90219. else {
  90220. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  90221. this._onBeforeActiveMeshesEvaluationObserver = null;
  90222. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  90223. this._onAfterActiveMeshesEvaluationObserver = null;
  90224. }
  90225. },
  90226. enumerable: true,
  90227. configurable: true
  90228. });
  90229. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  90230. /**
  90231. * Gets the perf counter used for render targets render time
  90232. */
  90233. get: function () {
  90234. return this._renderTargetsRenderTime;
  90235. },
  90236. enumerable: true,
  90237. configurable: true
  90238. });
  90239. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  90240. /**
  90241. * Gets the render targets render time capture status
  90242. */
  90243. get: function () {
  90244. return this._captureRenderTargetsRenderTime;
  90245. },
  90246. /**
  90247. * Enable or disable the render targets render time capture
  90248. */
  90249. set: function (value) {
  90250. var _this = this;
  90251. if (value === this._captureRenderTargetsRenderTime) {
  90252. return;
  90253. }
  90254. this._captureRenderTargetsRenderTime = value;
  90255. if (value) {
  90256. this._onBeforeRenderTargetsRenderObserver = this.scene.OnBeforeRenderTargetsRenderObservable.add(function () {
  90257. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  90258. _this._renderTargetsRenderTime.beginMonitoring();
  90259. });
  90260. this._onAfterRenderTargetsRenderObserver = this.scene.OnAfterRenderTargetsRenderObservable.add(function () {
  90261. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  90262. _this._renderTargetsRenderTime.endMonitoring(false);
  90263. });
  90264. }
  90265. else {
  90266. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  90267. this._onBeforeRenderTargetsRenderObserver = null;
  90268. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  90269. this._onAfterRenderTargetsRenderObserver = null;
  90270. }
  90271. },
  90272. enumerable: true,
  90273. configurable: true
  90274. });
  90275. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  90276. /**
  90277. * Gets the perf counter used for particles render time
  90278. */
  90279. get: function () {
  90280. return this._particlesRenderTime;
  90281. },
  90282. enumerable: true,
  90283. configurable: true
  90284. });
  90285. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  90286. /**
  90287. * Gets the particles render time capture status
  90288. */
  90289. get: function () {
  90290. return this._captureParticlesRenderTime;
  90291. },
  90292. /**
  90293. * Enable or disable the particles render time capture
  90294. */
  90295. set: function (value) {
  90296. var _this = this;
  90297. if (value === this._captureParticlesRenderTime) {
  90298. return;
  90299. }
  90300. this._captureParticlesRenderTime = value;
  90301. if (value) {
  90302. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  90303. BABYLON.Tools.StartPerformanceCounter("Particles");
  90304. _this._particlesRenderTime.beginMonitoring();
  90305. });
  90306. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  90307. BABYLON.Tools.EndPerformanceCounter("Particles");
  90308. _this._particlesRenderTime.endMonitoring(false);
  90309. });
  90310. }
  90311. else {
  90312. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  90313. this._onBeforeParticlesRenderingObserver = null;
  90314. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  90315. this._onAfterParticlesRenderingObserver = null;
  90316. }
  90317. },
  90318. enumerable: true,
  90319. configurable: true
  90320. });
  90321. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  90322. /**
  90323. * Gets the perf counter used for sprites render time
  90324. */
  90325. get: function () {
  90326. return this._spritesRenderTime;
  90327. },
  90328. enumerable: true,
  90329. configurable: true
  90330. });
  90331. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  90332. /**
  90333. * Gets the sprites render time capture status
  90334. */
  90335. get: function () {
  90336. return this._captureSpritesRenderTime;
  90337. },
  90338. /**
  90339. * Enable or disable the sprites render time capture
  90340. */
  90341. set: function (value) {
  90342. var _this = this;
  90343. if (value === this._captureSpritesRenderTime) {
  90344. return;
  90345. }
  90346. this._captureSpritesRenderTime = value;
  90347. if (value) {
  90348. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  90349. BABYLON.Tools.StartPerformanceCounter("Sprites");
  90350. _this._spritesRenderTime.beginMonitoring();
  90351. });
  90352. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  90353. BABYLON.Tools.EndPerformanceCounter("Sprites");
  90354. _this._spritesRenderTime.endMonitoring(false);
  90355. });
  90356. }
  90357. else {
  90358. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  90359. this._onBeforeSpritesRenderingObserver = null;
  90360. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  90361. this._onAfterSpritesRenderingObserver = null;
  90362. }
  90363. },
  90364. enumerable: true,
  90365. configurable: true
  90366. });
  90367. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  90368. /**
  90369. * Gets the perf counter used for physics time
  90370. */
  90371. get: function () {
  90372. return this._physicsTime;
  90373. },
  90374. enumerable: true,
  90375. configurable: true
  90376. });
  90377. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  90378. /**
  90379. * Gets the physics time capture status
  90380. */
  90381. get: function () {
  90382. return this._capturePhysicsTime;
  90383. },
  90384. /**
  90385. * Enable or disable the physics time capture
  90386. */
  90387. set: function (value) {
  90388. var _this = this;
  90389. if (value === this._capturePhysicsTime) {
  90390. return;
  90391. }
  90392. this._capturePhysicsTime = value;
  90393. if (value) {
  90394. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  90395. BABYLON.Tools.StartPerformanceCounter("Physics");
  90396. _this._physicsTime.beginMonitoring();
  90397. });
  90398. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  90399. BABYLON.Tools.EndPerformanceCounter("Physics");
  90400. _this._physicsTime.endMonitoring();
  90401. });
  90402. }
  90403. else {
  90404. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  90405. this._onBeforePhysicsObserver = null;
  90406. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  90407. this._onAfterPhysicsObserver = null;
  90408. }
  90409. },
  90410. enumerable: true,
  90411. configurable: true
  90412. });
  90413. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  90414. /**
  90415. * Gets the perf counter used for animations time
  90416. */
  90417. get: function () {
  90418. return this._animationsTime;
  90419. },
  90420. enumerable: true,
  90421. configurable: true
  90422. });
  90423. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  90424. /**
  90425. * Gets the animations time capture status
  90426. */
  90427. get: function () {
  90428. return this._captureAnimationsTime;
  90429. },
  90430. /**
  90431. * Enable or disable the animations time capture
  90432. */
  90433. set: function (value) {
  90434. var _this = this;
  90435. if (value === this._captureAnimationsTime) {
  90436. return;
  90437. }
  90438. this._captureAnimationsTime = value;
  90439. if (value) {
  90440. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  90441. _this._animationsTime.endMonitoring();
  90442. });
  90443. }
  90444. else {
  90445. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  90446. this._onAfterAnimationsObserver = null;
  90447. }
  90448. },
  90449. enumerable: true,
  90450. configurable: true
  90451. });
  90452. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  90453. /**
  90454. * Gets the perf counter used for frame time capture
  90455. */
  90456. get: function () {
  90457. return this._frameTime;
  90458. },
  90459. enumerable: true,
  90460. configurable: true
  90461. });
  90462. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  90463. /**
  90464. * Gets the frame time capture status
  90465. */
  90466. get: function () {
  90467. return this._captureFrameTime;
  90468. },
  90469. /**
  90470. * Enable or disable the frame time capture
  90471. */
  90472. set: function (value) {
  90473. this._captureFrameTime = value;
  90474. },
  90475. enumerable: true,
  90476. configurable: true
  90477. });
  90478. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  90479. /**
  90480. * Gets the perf counter used for inter-frames time capture
  90481. */
  90482. get: function () {
  90483. return this._interFrameTime;
  90484. },
  90485. enumerable: true,
  90486. configurable: true
  90487. });
  90488. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  90489. /**
  90490. * Gets the inter-frames time capture status
  90491. */
  90492. get: function () {
  90493. return this._captureInterFrameTime;
  90494. },
  90495. /**
  90496. * Enable or disable the inter-frames time capture
  90497. */
  90498. set: function (value) {
  90499. this._captureInterFrameTime = value;
  90500. },
  90501. enumerable: true,
  90502. configurable: true
  90503. });
  90504. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  90505. /**
  90506. * Gets the perf counter used for render time capture
  90507. */
  90508. get: function () {
  90509. return this._renderTime;
  90510. },
  90511. enumerable: true,
  90512. configurable: true
  90513. });
  90514. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  90515. /**
  90516. * Gets the render time capture status
  90517. */
  90518. get: function () {
  90519. return this._captureRenderTime;
  90520. },
  90521. /**
  90522. * Enable or disable the render time capture
  90523. */
  90524. set: function (value) {
  90525. var _this = this;
  90526. if (value === this._captureRenderTime) {
  90527. return;
  90528. }
  90529. this._captureRenderTime = value;
  90530. if (value) {
  90531. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  90532. _this._renderTime.beginMonitoring();
  90533. BABYLON.Tools.StartPerformanceCounter("Main render");
  90534. });
  90535. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  90536. _this._renderTime.endMonitoring(false);
  90537. BABYLON.Tools.EndPerformanceCounter("Main render");
  90538. });
  90539. }
  90540. else {
  90541. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  90542. this._onBeforeDrawPhaseObserver = null;
  90543. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  90544. this._onAfterDrawPhaseObserver = null;
  90545. }
  90546. },
  90547. enumerable: true,
  90548. configurable: true
  90549. });
  90550. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  90551. /**
  90552. * Gets the perf counter used for draw calls
  90553. */
  90554. get: function () {
  90555. return this.scene.getEngine()._drawCalls;
  90556. },
  90557. enumerable: true,
  90558. configurable: true
  90559. });
  90560. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  90561. /**
  90562. * Gets the perf counter used for texture collisions
  90563. */
  90564. get: function () {
  90565. return this.scene.getEngine()._textureCollisions;
  90566. },
  90567. enumerable: true,
  90568. configurable: true
  90569. });
  90570. SceneInstrumentation.prototype.dispose = function () {
  90571. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  90572. this._onAfterRenderObserver = null;
  90573. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  90574. this._onBeforeActiveMeshesEvaluationObserver = null;
  90575. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  90576. this._onAfterActiveMeshesEvaluationObserver = null;
  90577. this.scene.OnBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  90578. this._onBeforeRenderTargetsRenderObserver = null;
  90579. this.scene.OnAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  90580. this._onAfterRenderTargetsRenderObserver = null;
  90581. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  90582. this._onBeforeAnimationsObserver = null;
  90583. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  90584. this._onBeforeParticlesRenderingObserver = null;
  90585. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  90586. this._onAfterParticlesRenderingObserver = null;
  90587. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  90588. this._onBeforeSpritesRenderingObserver = null;
  90589. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  90590. this._onAfterSpritesRenderingObserver = null;
  90591. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  90592. this._onBeforeDrawPhaseObserver = null;
  90593. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  90594. this._onAfterDrawPhaseObserver = null;
  90595. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  90596. this._onBeforePhysicsObserver = null;
  90597. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  90598. this._onAfterPhysicsObserver = null;
  90599. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  90600. this._onAfterAnimationsObserver = null;
  90601. this.scene = null;
  90602. };
  90603. return SceneInstrumentation;
  90604. }());
  90605. BABYLON.SceneInstrumentation = SceneInstrumentation;
  90606. })(BABYLON || (BABYLON = {}));
  90607. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  90608. "use strict";
  90609. var BABYLON;
  90610. (function (BABYLON) {
  90611. var _TimeToken = /** @class */ (function () {
  90612. function _TimeToken() {
  90613. this._timeElapsedQueryEnded = false;
  90614. }
  90615. return _TimeToken;
  90616. }());
  90617. BABYLON._TimeToken = _TimeToken;
  90618. })(BABYLON || (BABYLON = {}));
  90619. //# sourceMappingURL=babylon.timeToken.js.map
  90620. "use strict";
  90621. var BABYLON;
  90622. (function (BABYLON) {
  90623. /**
  90624. * Background material defines definition.
  90625. * @ignore Mainly internal Use
  90626. */
  90627. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  90628. __extends(BackgroundMaterialDefines, _super);
  90629. /**
  90630. * Constructor of the defines.
  90631. */
  90632. function BackgroundMaterialDefines() {
  90633. var _this = _super.call(this) || this;
  90634. /**
  90635. * True if the diffuse texture is in use.
  90636. */
  90637. _this.DIFFUSE = false;
  90638. /**
  90639. * The direct UV channel to use.
  90640. */
  90641. _this.DIFFUSEDIRECTUV = 0;
  90642. /**
  90643. * True if the diffuse texture is in gamma space.
  90644. */
  90645. _this.GAMMADIFFUSE = false;
  90646. /**
  90647. * True if the diffuse texture has opacity in the alpha channel.
  90648. */
  90649. _this.DIFFUSEHASALPHA = false;
  90650. /**
  90651. * True if you want the material to fade to transparent at grazing angle.
  90652. */
  90653. _this.OPACITYFRESNEL = false;
  90654. /**
  90655. * True if an extra blur needs to be added in the reflection.
  90656. */
  90657. _this.REFLECTIONBLUR = false;
  90658. /**
  90659. * True if you want the material to fade to reflection at grazing angle.
  90660. */
  90661. _this.REFLECTIONFRESNEL = false;
  90662. /**
  90663. * True if you want the material to falloff as far as you move away from the scene center.
  90664. */
  90665. _this.REFLECTIONFALLOFF = false;
  90666. /**
  90667. * False if the current Webgl implementation does not support the texture lod extension.
  90668. */
  90669. _this.TEXTURELODSUPPORT = false;
  90670. /**
  90671. * True to ensure the data are premultiplied.
  90672. */
  90673. _this.PREMULTIPLYALPHA = false;
  90674. /**
  90675. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  90676. */
  90677. _this.USERGBCOLOR = false;
  90678. /**
  90679. * True to add noise in order to reduce the banding effect.
  90680. */
  90681. _this.NOISE = false;
  90682. /**
  90683. * is the reflection texture in BGR color scheme?
  90684. * Mainly used to solve a bug in ios10 video tag
  90685. */
  90686. _this.REFLECTIONBGR = false;
  90687. _this.IMAGEPROCESSING = false;
  90688. _this.VIGNETTE = false;
  90689. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  90690. _this.VIGNETTEBLENDMODEOPAQUE = false;
  90691. _this.TONEMAPPING = false;
  90692. _this.CONTRAST = false;
  90693. _this.COLORCURVES = false;
  90694. _this.COLORGRADING = false;
  90695. _this.COLORGRADING3D = false;
  90696. _this.SAMPLER3DGREENDEPTH = false;
  90697. _this.SAMPLER3DBGRMAP = false;
  90698. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  90699. _this.EXPOSURE = false;
  90700. _this.GRAIN = false;
  90701. // Reflection.
  90702. _this.REFLECTION = false;
  90703. _this.REFLECTIONMAP_3D = false;
  90704. _this.REFLECTIONMAP_SPHERICAL = false;
  90705. _this.REFLECTIONMAP_PLANAR = false;
  90706. _this.REFLECTIONMAP_CUBIC = false;
  90707. _this.REFLECTIONMAP_PROJECTION = false;
  90708. _this.REFLECTIONMAP_SKYBOX = false;
  90709. _this.REFLECTIONMAP_EXPLICIT = false;
  90710. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  90711. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  90712. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  90713. _this.INVERTCUBICMAP = false;
  90714. _this.REFLECTIONMAP_OPPOSITEZ = false;
  90715. _this.LODINREFLECTIONALPHA = false;
  90716. _this.GAMMAREFLECTION = false;
  90717. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  90718. // Default BJS.
  90719. _this.MAINUV1 = false;
  90720. _this.MAINUV2 = false;
  90721. _this.UV1 = false;
  90722. _this.UV2 = false;
  90723. _this.CLIPPLANE = false;
  90724. _this.POINTSIZE = false;
  90725. _this.FOG = false;
  90726. _this.NORMAL = false;
  90727. _this.NUM_BONE_INFLUENCERS = 0;
  90728. _this.BonesPerMesh = 0;
  90729. _this.INSTANCES = false;
  90730. _this.SHADOWFLOAT = false;
  90731. _this.rebuild();
  90732. return _this;
  90733. }
  90734. return BackgroundMaterialDefines;
  90735. }(BABYLON.MaterialDefines));
  90736. /**
  90737. * Background material used to create an efficient environement around your scene.
  90738. */
  90739. var BackgroundMaterial = /** @class */ (function (_super) {
  90740. __extends(BackgroundMaterial, _super);
  90741. /**
  90742. * Instantiates a Background Material in the given scene
  90743. * @param name The friendly name of the material
  90744. * @param scene The scene to add the material to
  90745. */
  90746. function BackgroundMaterial(name, scene) {
  90747. var _this = _super.call(this, name, scene) || this;
  90748. /**
  90749. * Key light Color (multiply against the R channel of the environement texture)
  90750. */
  90751. _this.primaryColor = BABYLON.Color3.White();
  90752. /**
  90753. * Key light Level (allowing HDR output of the background)
  90754. */
  90755. _this.primaryLevel = 1;
  90756. /**
  90757. * Secondary light Color (multiply against the G channel of the environement texture)
  90758. */
  90759. _this.secondaryColor = BABYLON.Color3.Gray();
  90760. /**
  90761. * Secondary light Level (allowing HDR output of the background)
  90762. */
  90763. _this.secondaryLevel = 1;
  90764. /**
  90765. * Tertiary light Color (multiply against the B channel of the environement texture)
  90766. */
  90767. _this.tertiaryColor = BABYLON.Color3.Black();
  90768. /**
  90769. * Tertiary light Level (allowing HDR output of the background)
  90770. */
  90771. _this.tertiaryLevel = 1;
  90772. /**
  90773. * Reflection Texture used in the material.
  90774. * Should be author in a specific way for the best result (refer to the documentation).
  90775. */
  90776. _this.reflectionTexture = null;
  90777. /**
  90778. * Reflection Texture level of blur.
  90779. *
  90780. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  90781. * texture twice.
  90782. */
  90783. _this.reflectionBlur = 0;
  90784. /**
  90785. * Diffuse Texture used in the material.
  90786. * Should be author in a specific way for the best result (refer to the documentation).
  90787. */
  90788. _this.diffuseTexture = null;
  90789. _this._shadowLights = null;
  90790. /**
  90791. * Specify the list of lights casting shadow on the material.
  90792. * All scene shadow lights will be included if null.
  90793. */
  90794. _this.shadowLights = null;
  90795. /**
  90796. * For the lights having a blurred shadow generator, this can add a second blur pass in order to reach
  90797. * soft lighting on the background.
  90798. */
  90799. _this.shadowBlurScale = 1;
  90800. /**
  90801. * Helps adjusting the shadow to a softer level if required.
  90802. * 0 means black shadows and 1 means no shadows.
  90803. */
  90804. _this.shadowLevel = 0;
  90805. /**
  90806. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  90807. * It is usually zero but might be interesting to modify according to your setup.
  90808. */
  90809. _this.sceneCenter = BABYLON.Vector3.Zero();
  90810. /**
  90811. * This helps specifying that the material is falling off to the sky box at grazing angle.
  90812. * This helps ensuring a nice transition when the camera goes under the ground.
  90813. */
  90814. _this.opacityFresnel = true;
  90815. /**
  90816. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  90817. * This helps adding a mirror texture on the ground.
  90818. */
  90819. _this.reflectionFresnel = false;
  90820. /**
  90821. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  90822. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  90823. */
  90824. _this.reflectionFalloffDistance = 0.0;
  90825. /**
  90826. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  90827. */
  90828. _this.reflectionAmount = 1.0;
  90829. /**
  90830. * This specifies the weight of the reflection at grazing angle.
  90831. */
  90832. _this.reflectionReflectance0 = 0.05;
  90833. /**
  90834. * This specifies the weight of the reflection at a perpendicular point of view.
  90835. */
  90836. _this.reflectionReflectance90 = 0.5;
  90837. /**
  90838. * Helps to directly use the maps channels instead of their level.
  90839. */
  90840. _this.useRGBColor = true;
  90841. /**
  90842. * This helps reducing the banding effect that could occur on the background.
  90843. */
  90844. _this.enableNoise = false;
  90845. _this._fovMultiplier = 1.0;
  90846. /**
  90847. * Enable the FOV adjustment feature controlled by fovMultiplier.
  90848. * @type {boolean}
  90849. */
  90850. _this.useEquirectangularFOV = false;
  90851. _this._maxSimultaneousLights = 4;
  90852. /**
  90853. * Number of Simultaneous lights allowed on the material.
  90854. */
  90855. _this.maxSimultaneousLights = 4;
  90856. /**
  90857. * Keep track of the image processing observer to allow dispose and replace.
  90858. */
  90859. _this._imageProcessingObserver = null;
  90860. /**
  90861. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  90862. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  90863. */
  90864. _this.switchToBGR = false;
  90865. // Temp values kept as cache in the material.
  90866. _this._renderTargets = new BABYLON.SmartArray(16);
  90867. _this._reflectionControls = BABYLON.Vector4.Zero();
  90868. // Setup the default processing configuration to the scene.
  90869. _this._attachImageProcessingConfiguration(null);
  90870. _this.getRenderTargetTextures = function () {
  90871. _this._renderTargets.reset();
  90872. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  90873. _this._renderTargets.push(_this._diffuseTexture);
  90874. }
  90875. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  90876. _this._renderTargets.push(_this._reflectionTexture);
  90877. }
  90878. return _this._renderTargets;
  90879. };
  90880. return _this;
  90881. }
  90882. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  90883. /**
  90884. * Sets the reflection reflectance fresnel values according to the default standard
  90885. * empirically know to work well :-)
  90886. */
  90887. set: function (value) {
  90888. var reflectionWeight = value;
  90889. if (reflectionWeight < 0.5) {
  90890. reflectionWeight = reflectionWeight * 2.0;
  90891. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  90892. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  90893. }
  90894. else {
  90895. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  90896. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  90897. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  90898. }
  90899. },
  90900. enumerable: true,
  90901. configurable: true
  90902. });
  90903. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  90904. /**
  90905. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  90906. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  90907. * Recommended to be keep at 1.0 except for special cases.
  90908. */
  90909. get: function () {
  90910. return this._fovMultiplier;
  90911. },
  90912. set: function (value) {
  90913. if (isNaN(value)) {
  90914. value = 1.0;
  90915. }
  90916. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  90917. },
  90918. enumerable: true,
  90919. configurable: true
  90920. });
  90921. /**
  90922. * Attaches a new image processing configuration to the PBR Material.
  90923. * @param configuration (if null the scene configuration will be use)
  90924. */
  90925. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  90926. var _this = this;
  90927. if (configuration === this._imageProcessingConfiguration) {
  90928. return;
  90929. }
  90930. // Detaches observer.
  90931. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  90932. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  90933. }
  90934. // Pick the scene configuration if needed.
  90935. if (!configuration) {
  90936. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  90937. }
  90938. else {
  90939. this._imageProcessingConfiguration = configuration;
  90940. }
  90941. // Attaches observer.
  90942. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  90943. _this._markAllSubMeshesAsImageProcessingDirty();
  90944. });
  90945. };
  90946. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  90947. /**
  90948. * Gets the image processing configuration used either in this material.
  90949. */
  90950. get: function () {
  90951. return this._imageProcessingConfiguration;
  90952. },
  90953. /**
  90954. * Sets the Default image processing configuration used either in the this material.
  90955. *
  90956. * If sets to null, the scene one is in use.
  90957. */
  90958. set: function (value) {
  90959. this._attachImageProcessingConfiguration(value);
  90960. // Ensure the effect will be rebuilt.
  90961. this._markAllSubMeshesAsTexturesDirty();
  90962. },
  90963. enumerable: true,
  90964. configurable: true
  90965. });
  90966. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  90967. /**
  90968. * Gets wether the color curves effect is enabled.
  90969. */
  90970. get: function () {
  90971. return this.imageProcessingConfiguration.colorCurvesEnabled;
  90972. },
  90973. /**
  90974. * Sets wether the color curves effect is enabled.
  90975. */
  90976. set: function (value) {
  90977. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  90978. },
  90979. enumerable: true,
  90980. configurable: true
  90981. });
  90982. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  90983. /**
  90984. * Gets wether the color grading effect is enabled.
  90985. */
  90986. get: function () {
  90987. return this.imageProcessingConfiguration.colorGradingEnabled;
  90988. },
  90989. /**
  90990. * Gets wether the color grading effect is enabled.
  90991. */
  90992. set: function (value) {
  90993. this.imageProcessingConfiguration.colorGradingEnabled = value;
  90994. },
  90995. enumerable: true,
  90996. configurable: true
  90997. });
  90998. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  90999. /**
  91000. * Gets wether tonemapping is enabled or not.
  91001. */
  91002. get: function () {
  91003. return this._imageProcessingConfiguration.toneMappingEnabled;
  91004. },
  91005. /**
  91006. * Sets wether tonemapping is enabled or not
  91007. */
  91008. set: function (value) {
  91009. this._imageProcessingConfiguration.toneMappingEnabled = value;
  91010. },
  91011. enumerable: true,
  91012. configurable: true
  91013. });
  91014. ;
  91015. ;
  91016. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  91017. /**
  91018. * The camera exposure used on this material.
  91019. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  91020. * This corresponds to a photographic exposure.
  91021. */
  91022. get: function () {
  91023. return this._imageProcessingConfiguration.exposure;
  91024. },
  91025. /**
  91026. * The camera exposure used on this material.
  91027. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  91028. * This corresponds to a photographic exposure.
  91029. */
  91030. set: function (value) {
  91031. this._imageProcessingConfiguration.exposure = value;
  91032. },
  91033. enumerable: true,
  91034. configurable: true
  91035. });
  91036. ;
  91037. ;
  91038. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  91039. /**
  91040. * Gets The camera contrast used on this material.
  91041. */
  91042. get: function () {
  91043. return this._imageProcessingConfiguration.contrast;
  91044. },
  91045. /**
  91046. * Sets The camera contrast used on this material.
  91047. */
  91048. set: function (value) {
  91049. this._imageProcessingConfiguration.contrast = value;
  91050. },
  91051. enumerable: true,
  91052. configurable: true
  91053. });
  91054. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  91055. /**
  91056. * Gets the Color Grading 2D Lookup Texture.
  91057. */
  91058. get: function () {
  91059. return this._imageProcessingConfiguration.colorGradingTexture;
  91060. },
  91061. /**
  91062. * Sets the Color Grading 2D Lookup Texture.
  91063. */
  91064. set: function (value) {
  91065. this.imageProcessingConfiguration.colorGradingTexture = value;
  91066. },
  91067. enumerable: true,
  91068. configurable: true
  91069. });
  91070. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  91071. /**
  91072. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  91073. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  91074. * 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;
  91075. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  91076. */
  91077. get: function () {
  91078. return this.imageProcessingConfiguration.colorCurves;
  91079. },
  91080. /**
  91081. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  91082. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  91083. * 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;
  91084. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  91085. */
  91086. set: function (value) {
  91087. this.imageProcessingConfiguration.colorCurves = value;
  91088. },
  91089. enumerable: true,
  91090. configurable: true
  91091. });
  91092. /**
  91093. * The entire material has been created in order to prevent overdraw.
  91094. * @returns false
  91095. */
  91096. BackgroundMaterial.prototype.needAlphaTesting = function () {
  91097. return true;
  91098. };
  91099. /**
  91100. * The entire material has been created in order to prevent overdraw.
  91101. * @returns true if blending is enable
  91102. */
  91103. BackgroundMaterial.prototype.needAlphaBlending = function () {
  91104. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  91105. };
  91106. /**
  91107. * Checks wether the material is ready to be rendered for a given mesh.
  91108. * @param mesh The mesh to render
  91109. * @param subMesh The submesh to check against
  91110. * @param useInstances Specify wether or not the material is used with instances
  91111. * @returns true if all the dependencies are ready (Textures, Effects...)
  91112. */
  91113. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  91114. var _this = this;
  91115. if (useInstances === void 0) { useInstances = false; }
  91116. if (subMesh.effect && this.isFrozen) {
  91117. if (this._wasPreviouslyReady) {
  91118. return true;
  91119. }
  91120. }
  91121. if (!subMesh._materialDefines) {
  91122. subMesh._materialDefines = new BackgroundMaterialDefines();
  91123. }
  91124. var scene = this.getScene();
  91125. var defines = subMesh._materialDefines;
  91126. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  91127. if (defines._renderId === scene.getRenderId()) {
  91128. return true;
  91129. }
  91130. }
  91131. var engine = scene.getEngine();
  91132. // Lights
  91133. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  91134. defines._needNormals = true;
  91135. // Textures
  91136. if (defines._areTexturesDirty) {
  91137. defines._needUVs = false;
  91138. if (scene.texturesEnabled) {
  91139. if (scene.getEngine().getCaps().textureLOD) {
  91140. defines.TEXTURELODSUPPORT = true;
  91141. }
  91142. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  91143. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  91144. return false;
  91145. }
  91146. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  91147. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  91148. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  91149. defines.OPACITYFRESNEL = this._opacityFresnel;
  91150. }
  91151. else {
  91152. defines.DIFFUSE = false;
  91153. defines.DIFFUSEHASALPHA = false;
  91154. defines.GAMMADIFFUSE = false;
  91155. defines.OPACITYFRESNEL = false;
  91156. }
  91157. var reflectionTexture = this._reflectionTexture;
  91158. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  91159. if (!reflectionTexture.isReadyOrNotBlocking()) {
  91160. return false;
  91161. }
  91162. defines.REFLECTION = true;
  91163. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  91164. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  91165. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  91166. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  91167. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  91168. defines.REFLECTIONBGR = this.switchToBGR;
  91169. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  91170. defines.INVERTCUBICMAP = true;
  91171. }
  91172. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  91173. switch (reflectionTexture.coordinatesMode) {
  91174. case BABYLON.Texture.CUBIC_MODE:
  91175. case BABYLON.Texture.INVCUBIC_MODE:
  91176. defines.REFLECTIONMAP_CUBIC = true;
  91177. break;
  91178. case BABYLON.Texture.EXPLICIT_MODE:
  91179. defines.REFLECTIONMAP_EXPLICIT = true;
  91180. break;
  91181. case BABYLON.Texture.PLANAR_MODE:
  91182. defines.REFLECTIONMAP_PLANAR = true;
  91183. break;
  91184. case BABYLON.Texture.PROJECTION_MODE:
  91185. defines.REFLECTIONMAP_PROJECTION = true;
  91186. break;
  91187. case BABYLON.Texture.SKYBOX_MODE:
  91188. defines.REFLECTIONMAP_SKYBOX = true;
  91189. break;
  91190. case BABYLON.Texture.SPHERICAL_MODE:
  91191. defines.REFLECTIONMAP_SPHERICAL = true;
  91192. break;
  91193. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  91194. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  91195. break;
  91196. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  91197. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  91198. break;
  91199. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  91200. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  91201. break;
  91202. }
  91203. if (this.reflectionFresnel) {
  91204. defines.REFLECTIONFRESNEL = true;
  91205. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  91206. this._reflectionControls.x = this.reflectionAmount;
  91207. this._reflectionControls.y = this.reflectionReflectance0;
  91208. this._reflectionControls.z = this.reflectionReflectance90;
  91209. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  91210. }
  91211. else {
  91212. defines.REFLECTIONFRESNEL = false;
  91213. defines.REFLECTIONFALLOFF = false;
  91214. }
  91215. }
  91216. else {
  91217. defines.REFLECTION = false;
  91218. defines.REFLECTIONFALLOFF = false;
  91219. defines.REFLECTIONBLUR = false;
  91220. defines.REFLECTIONMAP_3D = false;
  91221. defines.REFLECTIONMAP_SPHERICAL = false;
  91222. defines.REFLECTIONMAP_PLANAR = false;
  91223. defines.REFLECTIONMAP_CUBIC = false;
  91224. defines.REFLECTIONMAP_PROJECTION = false;
  91225. defines.REFLECTIONMAP_SKYBOX = false;
  91226. defines.REFLECTIONMAP_EXPLICIT = false;
  91227. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  91228. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  91229. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  91230. defines.INVERTCUBICMAP = false;
  91231. defines.REFLECTIONMAP_OPPOSITEZ = false;
  91232. defines.LODINREFLECTIONALPHA = false;
  91233. defines.GAMMAREFLECTION = false;
  91234. }
  91235. }
  91236. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  91237. defines.USERGBCOLOR = this._useRGBColor;
  91238. defines.NOISE = this._enableNoise;
  91239. }
  91240. if (defines._areImageProcessingDirty) {
  91241. if (!this._imageProcessingConfiguration.isReady()) {
  91242. return false;
  91243. }
  91244. this._imageProcessingConfiguration.prepareDefines(defines);
  91245. }
  91246. // Misc.
  91247. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  91248. // Values that need to be evaluated on every frame
  91249. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  91250. // Attribs
  91251. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  91252. if (mesh) {
  91253. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  91254. mesh.createNormals(true);
  91255. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  91256. }
  91257. }
  91258. }
  91259. // Get correct effect
  91260. if (defines.isDirty) {
  91261. defines.markAsProcessed();
  91262. scene.resetCachedMaterial();
  91263. // Fallbacks
  91264. var fallbacks = new BABYLON.EffectFallbacks();
  91265. if (defines.FOG) {
  91266. fallbacks.addFallback(0, "FOG");
  91267. }
  91268. if (defines.POINTSIZE) {
  91269. fallbacks.addFallback(1, "POINTSIZE");
  91270. }
  91271. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  91272. if (defines.NUM_BONE_INFLUENCERS > 0) {
  91273. fallbacks.addCPUSkinningFallback(0, mesh);
  91274. }
  91275. //Attributes
  91276. var attribs = [BABYLON.VertexBuffer.PositionKind];
  91277. if (defines.NORMAL) {
  91278. attribs.push(BABYLON.VertexBuffer.NormalKind);
  91279. }
  91280. if (defines.UV1) {
  91281. attribs.push(BABYLON.VertexBuffer.UVKind);
  91282. }
  91283. if (defines.UV2) {
  91284. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  91285. }
  91286. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  91287. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  91288. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  91289. "vFogInfos", "vFogColor", "pointSize",
  91290. "vClipPlane", "mBones",
  91291. "vPrimaryColor", "vSecondaryColor", "vTertiaryColor",
  91292. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  91293. "shadowLevel", "alpha",
  91294. "vBackgroundCenter", "vReflectionControl",
  91295. "vDiffuseInfos", "diffuseMatrix",
  91296. ];
  91297. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  91298. var uniformBuffers = ["Material", "Scene"];
  91299. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  91300. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  91301. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  91302. uniformsNames: uniforms,
  91303. uniformBuffersNames: uniformBuffers,
  91304. samplers: samplers,
  91305. defines: defines,
  91306. maxSimultaneousLights: this._maxSimultaneousLights
  91307. });
  91308. var onCompiled = function (effect) {
  91309. if (_this.onCompiled) {
  91310. _this.onCompiled(effect);
  91311. }
  91312. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  91313. };
  91314. var join = defines.toString();
  91315. subMesh.setEffect(scene.getEngine().createEffect("background", {
  91316. attributes: attribs,
  91317. uniformsNames: uniforms,
  91318. uniformBuffersNames: uniformBuffers,
  91319. samplers: samplers,
  91320. defines: join,
  91321. fallbacks: fallbacks,
  91322. onCompiled: onCompiled,
  91323. onError: this.onError,
  91324. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  91325. }, engine), defines);
  91326. this.buildUniformLayout();
  91327. }
  91328. if (!subMesh.effect || !subMesh.effect.isReady()) {
  91329. return false;
  91330. }
  91331. defines._renderId = scene.getRenderId();
  91332. this._wasPreviouslyReady = true;
  91333. return true;
  91334. };
  91335. /**
  91336. * Build the uniform buffer used in the material.
  91337. */
  91338. BackgroundMaterial.prototype.buildUniformLayout = function () {
  91339. // Order is important !
  91340. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  91341. this._uniformBuffer.addUniform("vSecondaryColor", 4);
  91342. this._uniformBuffer.addUniform("vTertiaryColor", 4);
  91343. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  91344. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  91345. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  91346. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  91347. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  91348. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  91349. this._uniformBuffer.addUniform("pointSize", 1);
  91350. this._uniformBuffer.addUniform("shadowLevel", 1);
  91351. this._uniformBuffer.addUniform("alpha", 1);
  91352. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  91353. this._uniformBuffer.addUniform("vReflectionControl", 4);
  91354. this._uniformBuffer.create();
  91355. };
  91356. /**
  91357. * Unbind the material.
  91358. */
  91359. BackgroundMaterial.prototype.unbind = function () {
  91360. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  91361. this._uniformBuffer.setTexture("diffuseSampler", null);
  91362. }
  91363. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  91364. this._uniformBuffer.setTexture("reflectionSampler", null);
  91365. }
  91366. _super.prototype.unbind.call(this);
  91367. };
  91368. /**
  91369. * Bind only the world matrix to the material.
  91370. * @param world The world matrix to bind.
  91371. */
  91372. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  91373. this._activeEffect.setMatrix("world", world);
  91374. };
  91375. /**
  91376. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  91377. * @param world The world matrix to bind.
  91378. * @param subMesh The submesh to bind for.
  91379. */
  91380. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  91381. var scene = this.getScene();
  91382. var defines = subMesh._materialDefines;
  91383. if (!defines) {
  91384. return;
  91385. }
  91386. var effect = subMesh.effect;
  91387. if (!effect) {
  91388. return;
  91389. }
  91390. this._activeEffect = effect;
  91391. // Matrices
  91392. this.bindOnlyWorldMatrix(world);
  91393. // Bones
  91394. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  91395. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  91396. if (mustRebind) {
  91397. this._uniformBuffer.bindToEffect(effect, "Material");
  91398. this.bindViewProjection(effect);
  91399. var reflectionTexture = this._reflectionTexture;
  91400. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  91401. // Texture uniforms
  91402. if (scene.texturesEnabled) {
  91403. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  91404. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  91405. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  91406. }
  91407. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  91408. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  91409. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  91410. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  91411. }
  91412. }
  91413. if (this.shadowLevel > 0) {
  91414. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  91415. }
  91416. this._uniformBuffer.updateFloat("alpha", this.alpha);
  91417. // Point size
  91418. if (this.pointsCloud) {
  91419. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  91420. }
  91421. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, this._primaryLevel);
  91422. this._uniformBuffer.updateColor4("vSecondaryColor", this._secondaryColor, this._secondaryLevel);
  91423. this._uniformBuffer.updateColor4("vTertiaryColor", this._tertiaryColor, this._tertiaryLevel);
  91424. }
  91425. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  91426. // Textures
  91427. if (scene.texturesEnabled) {
  91428. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  91429. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  91430. }
  91431. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  91432. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  91433. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  91434. }
  91435. else if (!defines.REFLECTIONBLUR) {
  91436. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  91437. }
  91438. else {
  91439. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  91440. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  91441. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  91442. }
  91443. if (defines.REFLECTIONFRESNEL) {
  91444. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  91445. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  91446. }
  91447. }
  91448. }
  91449. // Clip plane
  91450. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  91451. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  91452. }
  91453. if (mustRebind || !this.isFrozen) {
  91454. if (scene.lightsEnabled) {
  91455. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  91456. }
  91457. // View
  91458. this.bindView(effect);
  91459. // Fog
  91460. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  91461. // image processing
  91462. this._imageProcessingConfiguration.bind(this._activeEffect);
  91463. }
  91464. this._uniformBuffer.update();
  91465. this._afterBind(mesh);
  91466. };
  91467. /**
  91468. * Dispose the material.
  91469. * @param forceDisposeEffect Force disposal of the associated effect.
  91470. * @param forceDisposeTextures Force disposal of the associated textures.
  91471. */
  91472. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  91473. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  91474. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  91475. if (forceDisposeTextures) {
  91476. if (this.diffuseTexture) {
  91477. this.diffuseTexture.dispose();
  91478. }
  91479. if (this.reflectionTexture) {
  91480. this.reflectionTexture.dispose();
  91481. }
  91482. }
  91483. this._renderTargets.dispose();
  91484. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  91485. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  91486. }
  91487. _super.prototype.dispose.call(this, forceDisposeEffect);
  91488. };
  91489. /**
  91490. * Clones the material.
  91491. * @param name The cloned name.
  91492. * @returns The cloned material.
  91493. */
  91494. BackgroundMaterial.prototype.clone = function (name) {
  91495. var _this = this;
  91496. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  91497. };
  91498. /**
  91499. * Serializes the current material to its JSON representation.
  91500. * @returns The JSON representation.
  91501. */
  91502. BackgroundMaterial.prototype.serialize = function () {
  91503. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  91504. serializationObject.customType = "BABYLON.BackgroundMaterial";
  91505. return serializationObject;
  91506. };
  91507. /**
  91508. * Gets the class name of the material
  91509. * @returns "BackgroundMaterial"
  91510. */
  91511. BackgroundMaterial.prototype.getClassName = function () {
  91512. return "BackgroundMaterial";
  91513. };
  91514. /**
  91515. * Parse a JSON input to create back a background material.
  91516. * @param source The JSON data to parse
  91517. * @param scene The scene to create the parsed material in
  91518. * @param rootUrl The root url of the assets the material depends upon
  91519. * @returns the instantiated BackgroundMaterial.
  91520. */
  91521. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  91522. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  91523. };
  91524. /**
  91525. * Standard reflectance value at parallel view angle.
  91526. */
  91527. BackgroundMaterial.StandardReflectance0 = 0.05;
  91528. /**
  91529. * Standard reflectance value at grazing angle.
  91530. */
  91531. BackgroundMaterial.StandardReflectance90 = 0.5;
  91532. __decorate([
  91533. BABYLON.serializeAsColor3()
  91534. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  91535. __decorate([
  91536. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91537. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  91538. __decorate([
  91539. BABYLON.serialize()
  91540. ], BackgroundMaterial.prototype, "_primaryLevel", void 0);
  91541. __decorate([
  91542. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91543. ], BackgroundMaterial.prototype, "primaryLevel", void 0);
  91544. __decorate([
  91545. BABYLON.serializeAsColor3()
  91546. ], BackgroundMaterial.prototype, "_secondaryColor", void 0);
  91547. __decorate([
  91548. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91549. ], BackgroundMaterial.prototype, "secondaryColor", void 0);
  91550. __decorate([
  91551. BABYLON.serialize()
  91552. ], BackgroundMaterial.prototype, "_secondaryLevel", void 0);
  91553. __decorate([
  91554. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91555. ], BackgroundMaterial.prototype, "secondaryLevel", void 0);
  91556. __decorate([
  91557. BABYLON.serializeAsColor3()
  91558. ], BackgroundMaterial.prototype, "_tertiaryColor", void 0);
  91559. __decorate([
  91560. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91561. ], BackgroundMaterial.prototype, "tertiaryColor", void 0);
  91562. __decorate([
  91563. BABYLON.serialize()
  91564. ], BackgroundMaterial.prototype, "_tertiaryLevel", void 0);
  91565. __decorate([
  91566. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  91567. ], BackgroundMaterial.prototype, "tertiaryLevel", void 0);
  91568. __decorate([
  91569. BABYLON.serializeAsTexture()
  91570. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  91571. __decorate([
  91572. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91573. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  91574. __decorate([
  91575. BABYLON.serialize()
  91576. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  91577. __decorate([
  91578. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91579. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  91580. __decorate([
  91581. BABYLON.serializeAsTexture()
  91582. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  91583. __decorate([
  91584. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91585. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  91586. __decorate([
  91587. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91588. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  91589. __decorate([
  91590. BABYLON.serialize()
  91591. ], BackgroundMaterial.prototype, "_shadowBlurScale", void 0);
  91592. __decorate([
  91593. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91594. ], BackgroundMaterial.prototype, "shadowBlurScale", void 0);
  91595. __decorate([
  91596. BABYLON.serialize()
  91597. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  91598. __decorate([
  91599. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91600. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  91601. __decorate([
  91602. BABYLON.serializeAsVector3()
  91603. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  91604. __decorate([
  91605. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91606. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  91607. __decorate([
  91608. BABYLON.serialize()
  91609. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  91610. __decorate([
  91611. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91612. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  91613. __decorate([
  91614. BABYLON.serialize()
  91615. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  91616. __decorate([
  91617. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91618. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  91619. __decorate([
  91620. BABYLON.serialize()
  91621. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  91622. __decorate([
  91623. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91624. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  91625. __decorate([
  91626. BABYLON.serialize()
  91627. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  91628. __decorate([
  91629. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91630. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  91631. __decorate([
  91632. BABYLON.serialize()
  91633. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  91634. __decorate([
  91635. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91636. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  91637. __decorate([
  91638. BABYLON.serialize()
  91639. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  91640. __decorate([
  91641. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91642. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  91643. __decorate([
  91644. BABYLON.serialize()
  91645. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  91646. __decorate([
  91647. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91648. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  91649. __decorate([
  91650. BABYLON.serialize()
  91651. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  91652. __decorate([
  91653. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91654. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  91655. __decorate([
  91656. BABYLON.serialize()
  91657. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  91658. __decorate([
  91659. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  91660. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  91661. __decorate([
  91662. BABYLON.serializeAsImageProcessingConfiguration()
  91663. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  91664. return BackgroundMaterial;
  91665. }(BABYLON.PushMaterial));
  91666. BABYLON.BackgroundMaterial = BackgroundMaterial;
  91667. })(BABYLON || (BABYLON = {}));
  91668. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  91669. "use strict";
  91670. var __assign = (this && this.__assign) || Object.assign || function(t) {
  91671. for (var s, i = 1, n = arguments.length; i < n; i++) {
  91672. s = arguments[i];
  91673. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  91674. t[p] = s[p];
  91675. }
  91676. return t;
  91677. };
  91678. var BABYLON;
  91679. (function (BABYLON) {
  91680. /**
  91681. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  91682. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  91683. * It also helps with the default setup of your imageProcessing configuration.
  91684. */
  91685. var EnvironmentHelper = /** @class */ (function () {
  91686. /**
  91687. * constructor
  91688. * @param options
  91689. * @param scene The scene to add the material to
  91690. */
  91691. function EnvironmentHelper(options, scene) {
  91692. var _this = this;
  91693. this._errorHandler = function (message, exception) {
  91694. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  91695. };
  91696. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  91697. this._scene = scene;
  91698. this.onErrorObservable = new BABYLON.Observable();
  91699. this._setupBackground();
  91700. this._setupImageProcessing();
  91701. }
  91702. /**
  91703. * Creates the default options for the helper.
  91704. */
  91705. EnvironmentHelper._getDefaultOptions = function () {
  91706. return {
  91707. createGround: true,
  91708. groundSize: 15,
  91709. groundTexture: this._groundTextureCDNUrl,
  91710. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  91711. groundOpacity: 0.9,
  91712. enableGroundShadow: true,
  91713. groundShadowLevel: 0.5,
  91714. enableGroundMirror: false,
  91715. groundMirrorSizeRatio: 0.3,
  91716. groundMirrorBlurKernel: 64,
  91717. groundMirrorAmount: 1,
  91718. groundMirrorFresnelWeight: 1,
  91719. groundMirrorFallOffDistance: 0,
  91720. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  91721. groundYBias: 0.00001,
  91722. createSkybox: true,
  91723. skyboxSize: 20,
  91724. skyboxTexture: this._skyboxTextureCDNUrl,
  91725. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  91726. backgroundYRotation: 0,
  91727. sizeAuto: true,
  91728. rootPosition: BABYLON.Vector3.Zero(),
  91729. setupImageProcessing: true,
  91730. environmentTexture: this._environmentTextureCDNUrl,
  91731. cameraExposure: 0.8,
  91732. cameraContrast: 1.2,
  91733. toneMappingEnabled: true,
  91734. };
  91735. };
  91736. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  91737. /**
  91738. * Gets the root mesh created by the helper.
  91739. */
  91740. get: function () {
  91741. return this._rootMesh;
  91742. },
  91743. enumerable: true,
  91744. configurable: true
  91745. });
  91746. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  91747. /**
  91748. * Gets the skybox created by the helper.
  91749. */
  91750. get: function () {
  91751. return this._skybox;
  91752. },
  91753. enumerable: true,
  91754. configurable: true
  91755. });
  91756. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  91757. /**
  91758. * Gets the skybox texture created by the helper.
  91759. */
  91760. get: function () {
  91761. return this._skyboxTexture;
  91762. },
  91763. enumerable: true,
  91764. configurable: true
  91765. });
  91766. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  91767. /**
  91768. * Gets the skybox material created by the helper.
  91769. */
  91770. get: function () {
  91771. return this._skyboxMaterial;
  91772. },
  91773. enumerable: true,
  91774. configurable: true
  91775. });
  91776. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  91777. /**
  91778. * Gets the ground mesh created by the helper.
  91779. */
  91780. get: function () {
  91781. return this._ground;
  91782. },
  91783. enumerable: true,
  91784. configurable: true
  91785. });
  91786. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  91787. /**
  91788. * Gets the ground texture created by the helper.
  91789. */
  91790. get: function () {
  91791. return this._groundTexture;
  91792. },
  91793. enumerable: true,
  91794. configurable: true
  91795. });
  91796. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  91797. /**
  91798. * Gets the ground mirror created by the helper.
  91799. */
  91800. get: function () {
  91801. return this._groundMirror;
  91802. },
  91803. enumerable: true,
  91804. configurable: true
  91805. });
  91806. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  91807. /**
  91808. * Gets the ground mirror render list to helps pushing the meshes
  91809. * you wish in the ground reflection.
  91810. */
  91811. get: function () {
  91812. if (this._groundMirror) {
  91813. return this._groundMirror.renderList;
  91814. }
  91815. return null;
  91816. },
  91817. enumerable: true,
  91818. configurable: true
  91819. });
  91820. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  91821. /**
  91822. * Gets the ground material created by the helper.
  91823. */
  91824. get: function () {
  91825. return this._groundMaterial;
  91826. },
  91827. enumerable: true,
  91828. configurable: true
  91829. });
  91830. /**
  91831. * Updates the background according to the new options
  91832. * @param options
  91833. */
  91834. EnvironmentHelper.prototype.updateOptions = function (options) {
  91835. var newOptions = __assign({}, this._options, options);
  91836. if (this._ground && !newOptions.createGround) {
  91837. this._ground.dispose();
  91838. this._ground = null;
  91839. }
  91840. if (this._groundMaterial && !newOptions.createGround) {
  91841. this._groundMaterial.dispose();
  91842. this._groundMaterial = null;
  91843. }
  91844. if (this._groundTexture) {
  91845. if (this._options.groundTexture != newOptions.groundTexture) {
  91846. this._groundTexture.dispose();
  91847. this._groundTexture = null;
  91848. }
  91849. }
  91850. if (this._skybox && !newOptions.createSkybox) {
  91851. this._skybox.dispose();
  91852. this._skybox = null;
  91853. }
  91854. if (this._skyboxMaterial && !newOptions.createSkybox) {
  91855. this._skyboxMaterial.dispose();
  91856. this._skyboxMaterial = null;
  91857. }
  91858. if (this._skyboxTexture) {
  91859. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  91860. this._skyboxTexture.dispose();
  91861. this._skyboxTexture = null;
  91862. }
  91863. }
  91864. if (this._groundMirror && !newOptions.enableGroundMirror) {
  91865. this._groundMirror.dispose();
  91866. this._groundMirror = null;
  91867. }
  91868. if (this._scene.environmentTexture) {
  91869. if (this._options.environmentTexture != newOptions.environmentTexture) {
  91870. this._scene.environmentTexture.dispose();
  91871. }
  91872. }
  91873. this._options = newOptions;
  91874. this._setupBackground();
  91875. this._setupImageProcessing();
  91876. };
  91877. /**
  91878. * Sets the primary color of all the available elements.
  91879. * @param color
  91880. */
  91881. EnvironmentHelper.prototype.setMainColor = function (color) {
  91882. if (this.groundMaterial) {
  91883. this.groundMaterial.primaryColor = color;
  91884. }
  91885. if (this.skyboxMaterial) {
  91886. this.skyboxMaterial.primaryColor = color;
  91887. }
  91888. if (this.groundMirror) {
  91889. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  91890. }
  91891. };
  91892. /**
  91893. * Setup the image processing according to the specified options.
  91894. */
  91895. EnvironmentHelper.prototype._setupImageProcessing = function () {
  91896. if (this._options.setupImageProcessing) {
  91897. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  91898. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  91899. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  91900. this._setupEnvironmentTexture();
  91901. }
  91902. };
  91903. /**
  91904. * Setup the environment texture according to the specified options.
  91905. */
  91906. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  91907. if (this._scene.environmentTexture) {
  91908. return;
  91909. }
  91910. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  91911. this._scene.environmentTexture = this._options.environmentTexture;
  91912. return;
  91913. }
  91914. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  91915. this._scene.environmentTexture = environmentTexture;
  91916. };
  91917. /**
  91918. * Setup the background according to the specified options.
  91919. */
  91920. EnvironmentHelper.prototype._setupBackground = function () {
  91921. if (!this._rootMesh) {
  91922. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  91923. }
  91924. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  91925. var sceneSize = this._getSceneSize();
  91926. if (this._options.createGround) {
  91927. this._setupGround(sceneSize);
  91928. this._setupGroundMaterial();
  91929. this._setupGroundDiffuseTexture();
  91930. if (this._options.enableGroundMirror) {
  91931. this._setupGroundMirrorTexture(sceneSize);
  91932. }
  91933. this._setupMirrorInGroundMaterial();
  91934. }
  91935. if (this._options.createSkybox) {
  91936. this._setupSkybox(sceneSize);
  91937. this._setupSkyboxMaterial();
  91938. this._setupSkyboxReflectionTexture();
  91939. }
  91940. this._rootMesh.position.x = sceneSize.rootPosition.x;
  91941. this._rootMesh.position.z = sceneSize.rootPosition.z;
  91942. this._rootMesh.position.y = sceneSize.rootPosition.y;
  91943. };
  91944. /**
  91945. * Get the scene sizes according to the setup.
  91946. */
  91947. EnvironmentHelper.prototype._getSceneSize = function () {
  91948. var _this = this;
  91949. var groundSize = this._options.groundSize;
  91950. var skyboxSize = this._options.skyboxSize;
  91951. var rootPosition = this._options.rootPosition;
  91952. if (!this._scene.meshes || this._scene.meshes.length === 1) {
  91953. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  91954. }
  91955. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  91956. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  91957. });
  91958. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  91959. if (this._options.sizeAuto) {
  91960. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  91961. this._scene.activeCamera.upperRadiusLimit) {
  91962. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  91963. skyboxSize = groundSize;
  91964. }
  91965. var sceneDiagonalLenght = sceneDiagonal.length();
  91966. if (sceneDiagonalLenght > groundSize) {
  91967. groundSize = sceneDiagonalLenght * 2;
  91968. skyboxSize = groundSize;
  91969. }
  91970. // 10 % bigger.
  91971. groundSize *= 1.1;
  91972. skyboxSize *= 1.5;
  91973. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  91974. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  91975. }
  91976. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  91977. };
  91978. /**
  91979. * Setup the ground according to the specified options.
  91980. */
  91981. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  91982. var _this = this;
  91983. if (!this._ground) {
  91984. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  91985. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  91986. this._ground.parent = this._rootMesh;
  91987. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  91988. }
  91989. this._ground.receiveShadows = this._options.enableGroundShadow;
  91990. };
  91991. /**
  91992. * Setup the ground material according to the specified options.
  91993. */
  91994. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  91995. if (!this._groundMaterial) {
  91996. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  91997. }
  91998. this._groundMaterial.alpha = this._options.groundOpacity;
  91999. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  92000. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  92001. this._groundMaterial.primaryLevel = 1;
  92002. this._groundMaterial.primaryColor = this._options.groundColor;
  92003. this._groundMaterial.secondaryLevel = 0;
  92004. this._groundMaterial.tertiaryLevel = 0;
  92005. this._groundMaterial.useRGBColor = false;
  92006. this._groundMaterial.enableNoise = true;
  92007. if (this._ground) {
  92008. this._ground.material = this._groundMaterial;
  92009. }
  92010. };
  92011. /**
  92012. * Setup the ground diffuse texture according to the specified options.
  92013. */
  92014. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  92015. if (!this._groundMaterial) {
  92016. return;
  92017. }
  92018. if (this._groundTexture) {
  92019. return;
  92020. }
  92021. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  92022. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  92023. return;
  92024. }
  92025. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  92026. diffuseTexture.gammaSpace = false;
  92027. diffuseTexture.hasAlpha = true;
  92028. this._groundMaterial.diffuseTexture = diffuseTexture;
  92029. };
  92030. /**
  92031. * Setup the ground mirror texture according to the specified options.
  92032. */
  92033. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  92034. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92035. if (!this._groundMirror) {
  92036. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  92037. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  92038. this._groundMirror.anisotropicFilteringLevel = 1;
  92039. this._groundMirror.wrapU = wrapping;
  92040. this._groundMirror.wrapV = wrapping;
  92041. this._groundMirror.gammaSpace = false;
  92042. if (this._groundMirror.renderList) {
  92043. for (var i = 0; i < this._scene.meshes.length; i++) {
  92044. var mesh = this._scene.meshes[i];
  92045. if (mesh !== this._ground &&
  92046. mesh !== this._skybox &&
  92047. mesh !== this._rootMesh) {
  92048. this._groundMirror.renderList.push(mesh);
  92049. }
  92050. }
  92051. }
  92052. }
  92053. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  92054. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  92055. };
  92056. /**
  92057. * Setup the ground to receive the mirror texture.
  92058. */
  92059. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  92060. if (this._groundMaterial) {
  92061. this._groundMaterial.reflectionTexture = this._groundMirror;
  92062. this._groundMaterial.reflectionFresnel = true;
  92063. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  92064. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  92065. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  92066. }
  92067. };
  92068. /**
  92069. * Setup the skybox according to the specified options.
  92070. */
  92071. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  92072. var _this = this;
  92073. if (!this._skybox) {
  92074. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  92075. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  92076. }
  92077. this._skybox.parent = this._rootMesh;
  92078. };
  92079. /**
  92080. * Setup the skybox material according to the specified options.
  92081. */
  92082. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  92083. if (!this._skybox) {
  92084. return;
  92085. }
  92086. if (!this._skyboxMaterial) {
  92087. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  92088. }
  92089. this._skyboxMaterial.useRGBColor = false;
  92090. this._skyboxMaterial.primaryLevel = 1;
  92091. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  92092. this._skyboxMaterial.secondaryLevel = 0;
  92093. this._skyboxMaterial.tertiaryLevel = 0;
  92094. this._skyboxMaterial.enableNoise = true;
  92095. this._skybox.material = this._skyboxMaterial;
  92096. };
  92097. /**
  92098. * Setup the skybox reflection texture according to the specified options.
  92099. */
  92100. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  92101. if (!this._skyboxMaterial) {
  92102. return;
  92103. }
  92104. if (this._skyboxTexture) {
  92105. return;
  92106. }
  92107. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  92108. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  92109. return;
  92110. }
  92111. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  92112. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  92113. this._skyboxTexture.gammaSpace = false;
  92114. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  92115. };
  92116. /**
  92117. * Dispose all the elements created by the Helper.
  92118. */
  92119. EnvironmentHelper.prototype.dispose = function () {
  92120. if (this._groundMaterial) {
  92121. this._groundMaterial.dispose(true, true);
  92122. }
  92123. if (this._skyboxMaterial) {
  92124. this._skyboxMaterial.dispose(true, true);
  92125. }
  92126. this._rootMesh.dispose(false);
  92127. };
  92128. /**
  92129. * Default ground texture URL.
  92130. */
  92131. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  92132. /**
  92133. * Default skybox texture URL.
  92134. */
  92135. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  92136. /**
  92137. * Default environment texture URL.
  92138. */
  92139. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  92140. return EnvironmentHelper;
  92141. }());
  92142. BABYLON.EnvironmentHelper = EnvironmentHelper;
  92143. })(BABYLON || (BABYLON = {}));
  92144. //# sourceMappingURL=babylon.environmentHelper.js.map
  92145. "use strict";
  92146. var BABYLON;
  92147. (function (BABYLON) {
  92148. /**
  92149. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  92150. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  92151. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  92152. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  92153. */
  92154. var VideoDome = /** @class */ (function (_super) {
  92155. __extends(VideoDome, _super);
  92156. /**
  92157. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  92158. * @param name Element's name, child elements will append suffixes for their own names.
  92159. * @param urlsOrVideo
  92160. * @param options An object containing optional or exposed sub element properties:
  92161. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  92162. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  92163. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  92164. * @param options **loop=true** Automatically loop video on end.
  92165. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  92166. */
  92167. function VideoDome(name, urlsOrVideo, options, scene) {
  92168. var _this = _super.call(this, name, scene) || this;
  92169. // set defaults and manage values
  92170. name = name || "videoDome";
  92171. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  92172. options.clickToPlay = Boolean(options.clickToPlay);
  92173. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  92174. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  92175. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  92176. // create
  92177. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  92178. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  92179. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  92180. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  92181. flat: false,
  92182. radius: options.size,
  92183. subdivisions: options.resolution,
  92184. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  92185. }, scene);
  92186. // configure material
  92187. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  92188. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  92189. material.reflectionTexture = _this._videoTexture;
  92190. material.useEquirectangularFOV = true;
  92191. material.fovMultiplier = 1.0;
  92192. // configure mesh
  92193. _this._mesh.material = material;
  92194. _this._mesh.parent = _this;
  92195. // optional configuration
  92196. if (options.clickToPlay) {
  92197. scene.onPointerUp = function () {
  92198. _this._videoTexture.video.play();
  92199. };
  92200. }
  92201. return _this;
  92202. }
  92203. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  92204. /**
  92205. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  92206. * Also see the options.resolution property.
  92207. */
  92208. get: function () {
  92209. return this._material.fovMultiplier;
  92210. },
  92211. set: function (value) {
  92212. this._material.fovMultiplier = value;
  92213. },
  92214. enumerable: true,
  92215. configurable: true
  92216. });
  92217. /**
  92218. * Releases resources associated with this node.
  92219. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  92220. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  92221. */
  92222. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  92223. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  92224. this._videoTexture.dispose();
  92225. this._mesh.dispose();
  92226. this._material.dispose();
  92227. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  92228. };
  92229. return VideoDome;
  92230. }(BABYLON.Node));
  92231. BABYLON.VideoDome = VideoDome;
  92232. })(BABYLON || (BABYLON = {}));
  92233. //# sourceMappingURL=babylon.videoDome.js.map
  92234. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb);\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/particlesInfos.z);\nfloat columnOffset=cellIndex-rowOffset*particlesInfos.z;\nvec2 uvScale=particlesInfos.xy;\nvec2 uvOffset=vec2(offset.x ,1.0-offset.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else\nvUV=offset;\n#endif\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","gpuRenderParticlesVertexShader":"#version 300 es\nuniform vec4 colorDead;\nuniform mat4 view;\nuniform mat4 projection;\n\nin vec3 position;\nin float age;\nin float life;\nin float size;\nin vec4 color;\nin vec2 offset;\nin vec2 uv;\nout vec2 vUV;\nout vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nout float fClipDistance;\n#endif\nvoid main() {\nvUV=uv;\nfloat ratio=age/life;\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n\nvec4 viewPosition=view*vec4(position,1.0);\ngl_Position=projection*(viewPosition+vec4(offset*size,0.,0.));\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*viewPosition;\nfClipDistance=dot(worldPos,vClipPlane);\n#endif \n}","gpuRenderParticlesPixelShader":"#version 300 es\nuniform sampler2D textureSampler;\nin vec2 vUV;\nin vec4 vColor;\nout vec4 outFragColor;\n#ifdef CLIPPLANE\nin float fClipDistance;\n#endif\nvoid main() {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif \noutFragColor=texture(textureSampler,vUV)*vColor;\n}\n","gpuUpdateParticlesVertexShader":"#version 300 es\n#define PI 3.14159\nuniform float currentCount;\nuniform float timeDelta;\nuniform float stopFactor;\nuniform vec3 generalRandoms;\nuniform mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 color1;\nuniform vec4 color2;\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform float radius;\nuniform float angle;\nuniform float height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin float seed;\nin float size;\nin vec4 color;\nin vec3 direction;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout float outSeed;\nout float outSize;\nout vec4 outColor;\nout vec3 outDirection;\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0)).rgb;\n}\nvec4 getRandomVec4(float offset) {\nreturn texture(randomSampler,vec2(float(gl_VertexID)*offset/currentCount,0));\n}\nvoid main() {\nif (age>=life) {\nif (stopFactor == 0.) {\noutPosition=position;\noutAge=life;\noutLife=life;\noutSeed=seed;\noutColor=vec4(0.,0.,0.,0.);\noutSize=0.;\noutDirection=direction;\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(generalRandoms.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\noutSize=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n\noutColor=color1+(color2-color1)*randoms.b;\n\n#ifdef BOXEMITTER\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nvec3 randoms3=getRandomVec3(generalRandoms.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=PI*randoms2.y;\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius*randoms2.z)*vec3(randX,randY,randZ);\n#ifdef DIRECTEDSPHEREEMITTER\ndirection=direction1+(direction2-direction1)*randoms3;\n#else\n\ndirection=position+directionRandomizer*randoms3;\n#endif\n#elif defined(CONEEMITTER)\nvec3 randoms2=getRandomVec3(generalRandoms.y);\nfloat s=2.0*PI*randoms2.x;\nfloat h=randoms2.y;\n\nh=1.-h*h;\nfloat lRadius=radius*randoms2.z;\nlRadius=lRadius*h/height;\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\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{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(position,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\ngl_FragColor=original;\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\n#ifdef DOF\nfloat sumOfWeights=0.0; \nfloat sampleDepth=0.0;\nfloat factor=0.0;\nfloat centerSampleDepth=sampleDistance(sampleCenter);\n#endif\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\n\nif(sumOfWeights == 0.0){\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"\nuniform sampler2D textureSampler;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\nvec4 original=texture2D(textureSampler,vUV);\n#if BLUR_LEVEL == 0\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\nif(coc<0.5){\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\nif(coc<0.33){\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(depthSampler,offset).r; \nreturn (cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \n}\nvoid main(void)\n{\nfloat pixelDistance=sampleDistance(vUV);\nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,texture2D(depthSampler,vUV).r,coc,1.0);\n}\n","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\n#ifdef GRAIN\nvec2 seed=vUV*(grainAnimatedSeed);\nfloat grain=dither(seed,grainVarianceAmount);\n\nfloat lum=getLuminance(result.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\nresult.rgb+=grain*grainAmount;\nresult.rgb=max(result.rgb,0.0);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\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{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec3 reflectionColor=vec3(1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor=reflectionColor.bgr;\n#endif\n\nreflectionColor*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\nvec3 finalColor=colorBase.r*vPrimaryColor.rgb*vPrimaryColor.a;\nfinalColor+=colorBase.g*vSecondaryColor.rgb*vSecondaryColor.a;\nfinalColor+=colorBase.b*vTertiaryColor.rgb*vTertiaryColor.a;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifndef GRAIN \n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\n#endif\ngl_FragColor=color;\n}\n"};
  92235. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\n#ifdef PBR\ntextureColor=toLinearSpace(textureColor);\n#endif\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=vDirectionW;\nfloat t=clamp(direction.y*-0.5+0.5,0.,1.0);\nfloat s=atan(direction.z,direction.x)*RECIPROCAL_PI2+0.5;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\nvec3 r=reflect(cameraToVertex,worldNormal);\nfloat t=clamp(r.y*-0.5+0.5,0.,1.0);\nfloat s=atan(r.z,r.x)*RECIPROCAL_PI2+0.5;\nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif\n#ifdef GRAIN\nuniform float grainVarianceAmount;\nuniform float grainAnimatedSeed;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","kernelBlurFragment":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nsampleDepth=sampleDistance(sampleCoord{X});\nfactor=clamp(1.0-((centerSampleDepth-sampleDepth)/centerSampleDepth),0.0,1.0);\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vSecondaryColor;\nuniform vec4 vTertiaryColor;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  92236. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  92237. globalObject["BABYLON"] = BABYLON
  92238. return BABYLON;
  92239. });